从现有对象创建新对象时,是Copy Constructor。 当已初始化的对象从另一个现有对象中分配了新值时,是Assignment Operator。当然,看到这句话,你还是不懂.下面看一下代码
#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;
}
};
// Driver code
int main()
{
Test t1, t2;
t2 = t1; //这里是Assignmeng operator
Test t3 = t1; //这里是copy constrctor
getchar();
return 0;
}
看到代码是不是清楚了些,不过你记得小时候这样的代码
#include<iostream>
#include<stdio.h>
using namespace std;
class Test
{
public:
Test() {}
int a = 0;
};
// Driver code
int main()
{
Test t1, t2;
t1.a = 3;
t2 = t1;
cout << t2.a << endl; //输出3
Test t3 = t1;
cout << t3.a << endl; //输出3
getchar();
return 0;
}
你没有写copy construct 怎么也会赋值上,这是因为编译器偷偷的给你把copy construct和assignment operator写上去了. 可以这样搞一下
#include<iostream>
#include<stdio.h>
using namespace std;
class Test
{
public:
Test() {}
int a = 0;
Test(const Test &t) = delete;
Test& operator = (const Test &t) = delete;
};
// Driver code
int main()
{
Test t1, t2;
t1.a = 3;
t2 = t1; //编译错误
cout << t2.a << endl;
Test t3 = t1; //编译错误
cout << t3.a << endl;
getchar();
return 0;
}
这样,就相当于你警告编译器不要多事.