参考下面的程序:
#include<iostream>
#include<stdio.h>
using namespace std;
class Test {
public:
Test() {}
Test(const Test& t) { cout << "Copy constructor called " << endl; }
Test& operator = (const Test& t) {
cout << "Assignment operator called " << endl;
return *this;
}
};
int main() {
Test t1, t2;
t2 = t1;
Test t3 = t1;
getchar();
return 0;
}
运行结果:
Assignment operator called
Copy constructor called
当使用一个已存在对象来创建新的对象时,就会调用拷贝构造函数。而赋值操作符用于将一个已存在对象赋值给另外一个已存在对象。
t2 = t1; // 调用赋值操作符, 相当于"t2.operator=(t1);"
Test t3 = t1; // 调用拷贝构造函数,相当于"Test t3(t1);"