C++ Primer 第四版,第619页:
Panda ying_yang("ying_yang"); //create a Panda object
Panda ling_ling = ying_yang //uses copy constructor
起初对于第二个语句调用复制构造函数很诧异,感觉应当调用赋值操作符函数。其实不然,请看如下代码:
代码
#include <iostream>
using namespace std;
class base{
public:
base() : i(0)
{
cout << "Default construction" << endl;
}
base(const base& rhs): i(rhs.i)
{
cout << "copy construction" << endl;
}
operator=(const base& rhs)
{
i = rhs.i;
cout << "复制操作符" << endl;
}
private:
int i;
};
int main()
{
base b;
base b1 = b;
base b2;
b2 = b;
}
using namespace std;
class base{
public:
base() : i(0)
{
cout << "Default construction" << endl;
}
base(const base& rhs): i(rhs.i)
{
cout << "copy construction" << endl;
}
operator=(const base& rhs)
{
i = rhs.i;
cout << "复制操作符" << endl;
}
private:
int i;
};
int main()
{
base b;
base b1 = b;
base b2;
b2 = b;
}
运行结果:
说明,关于Panda ling_ling = ying_yang; 调用的是复制构造函数,因为这个语句执行的时候,ling_ling对象还没有被创建,被初始化,不能执行赋值操作符,所以必须执行复制构造函数,创建对象。
另外,一旦一个类定义了一个构造函数,那么编译器就不会为之合成合成的默认构造函数了。