#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解决 无用评论 打赏 举报