#include <iostream>
using namespace std;
class CTest
{
public:
CTest(int aa): a(aa) { cout << "constructor: a = " << a << endl; }
CTest(const CTest &in)
{
a = in.a;
cout << "copy constructor" << endl;
}
~CTest() { cout << "desctructor: a = " << a << endl; }
CTest& operator=(const CTest &in)
{
a = in.a;
cout << "operator=" << endl;
return *this;
}
public:
int a;
};
int main()
{
CTest test1 = CTest(10); // 调用普通构造函数初始化(直接初始化)
CTest test2(CTest(11)); // 调用普通构造函数初始化(直接初始化)
CTest test3(test1); // 调用拷贝构造函数初始化
CTest test4 = test1; // 调用拷贝构造函数初始化
test4 = test2; // 赋值操作符
cout << "end" << endl;
return 0;
}
输出:
constructor: a = 10
constructor: a = 11
copy constructor
copy constructor
operator=
end
desctructor: a = 11
desctructor: a = 10
desctructor: a = 11
desctructor: a = 10
1. 编译器会默认添加拷贝构造函数和拷贝赋值操作符(=),当然,用户也可以自己写,即重载;
2. "=" 在不同时期含义不同:初始化时期 "=" 调用的是“拷贝构造函数”(如果右边是非临时对象,如 CTest test4 = test1, ),后期赋值是调用的“拷贝赋值操作符”(如 test4 = test2);
3. 区分什么时候是调用普通构造函数初始化(直接初始化),什么时候是调用拷贝构造函数初始化。如 CTest test1 = CTest(10) 和 CTest test2(CTest(11)) 都是直接初始化。