很早知道拷贝构造函数被调用有三种情况:
1)类对象初始化该类的另一对象时;
2)形参为类对象的函数被调用时;
3)返回值为类对象的函数执行完成返回调用者时。
但今天才发现理解的和实际情况有偏差,并不是出现赋值运算符=就是调用的赋值操作运算符函数啊,比如这里的1),类对象初始化另一对象时是可以用拷贝构造函数形式,也可以利用赋值符号的形式啊,类似内置类型的初始化,用一个简单的类来验证了该事实。
#include <iostream>
#include <string>
using namespace std;
int main()
{
class Foo{
public:
Foo()
{
myFun("This is from default constructor--Build-in type is not initialized!");
}
Foo(const Foo& rhs)
{
this->a = rhs.a+1;
this->s = rhs.s;
myFun("This is from copy constructor");
}
Foo& operator=(const Foo& rhs)
{
this->a = rhs.a+2;
this->s = rhs.s;
myFun("This is from =operator");
return *this;
}
Foo(int aa, string ss):a(aa),s(ss)
{
myFun("This is from constructor with Constructor Initializer List");
}
~Foo(){}
void myFun(string str)
{
cout << a << ends << s << endl << str << endl;
}
private:
int a;
string s;
};
Foo foo(3,"good");
Foo foo1;//初始化
Foo foo2=foo;
Foo foo3(foo);
foo1=foo;//这才是赋值
return 0;
}
运行结果:从结果可以看出只有最后一句才是来自赋值运算符,其上两个来自拷贝构造函数。