一般对于初始化类变量有两种方式:
A a;
A b = a;
另一种方式是:
A a ;
A b;
a =b;
对于第一种方式,编译器相当于在b的初始化的时候,用a的引用作为复制构造函数的参数进行操作,相当于A b(a);
而对于第二种方式,则应该是用了赋值构造函数,也就是=的重载。因为a和b本身都已经重载了,就相当于把b的值赋给a了。
比如代码如下:
class mytest{
public:
int a;
mytest(int s) :a(s){};//构造函数
mytest(const mytest & test){//复制构造函数
a = test.a;
cout << "copy constructor used!" << endl;
}
void operator = (const mytest & test){//赋值构造函数
a = test.a;
cout << "copy assignment used!" << endl;
//return *this;
}
};
int main(){
mytest test1(2);
mytest test2 = test1;
cout << "---------------" << endl;
mytest test3(2);
test3 = test1;
cout << "---------------" << endl;
cout << "value of a in test2 is: " << test2.a << endl;
cout << "value of a in test3 is: " << test3.a << endl;
system("pause");
return 0;
}
它的输出是:
需要注意的是,如果我把赋值构造函数的返回值设定为A类对象,由复制构造函数的用法,则赋值构造函数里面还会再次调用复制构造函数,比如:
class mytest{
public:
int a;
mytest(int s) :a(s){};//构造函数
mytest(const mytest & test){//复制构造函数
a = test.a;
cout << "copy constructor used!" << endl;
}
mytest operator = (const mytest & test){//赋值构造函数
a = test.a;
cout << "copy assignment used!" << endl;
return *this;
}
};
int main(){
mytest test1(2);
mytest test2 = test1;
cout << "---------------" << endl;
mytest test3(2);
test3 = test1;
cout << "---------------" << endl;
cout << "value of a in test2 is: " << test2.a << endl;
cout << "value of a in test3 is: " << test3.a << endl;
system("pause");
return 0;
}
它的结果就是: