#include <iostream>
using namespace std;
class A
{
int a,b;
public:
A(int i,int j):a(i),b(j){cout<<"constructor"<<endl;}
~A(){cout<<"destructor"<<endl;}
};
int main()
{
A obj1(1,2);
A obj2=obj1;
return 0;
}
运行结果为什么只有一个constructor呢?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
3条回答
关注 因为以下的赋值并没有调用它的显式构造函数,而是调用编译器生成的隐式拷贝构造函数。
A obj2=obj1;
如果我们自己写显式拷贝构造函数,就会打印。
// test-c11.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; class A { int a, b; public: A(int i, int j) :a(i), b(j) { cout << "constructor" << endl; } A(A& a1) { a = a1.a; b = a1.b; cout << "copy constructor" << endl; } ~A() { cout << "destructor" << endl; } }; int main() { A obj1(1, 2); A obj2 = obj1; return 0; }
输出
constructor copy constructor destructor destructor
解决 无用评论 打赏 举报
悬赏问题
- ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
- ¥15 如何在scanpy上做差异基因和通路富集?
- ¥20 关于#硬件工程#的问题,请各位专家解答!
- ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
- ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
- ¥30 截图中的mathematics程序转换成matlab
- ¥15 动力学代码报错,维度不匹配
- ¥15 Power query添加列问题
- ¥50 Kubernetes&Fission&Eleasticsearch
- ¥15 報錯:Person is not mapped,如何解決?