拷贝构造函数:是一种特殊的构造函数,函数的名称必须和类名称一致,它必须的一个参数是本类型的一个引用变量。
CExample(const CExample& C) ;
class CExample
{
private:
int a;
public:
//构造函数
CExample(int b)
{
a = b;
cout<<"creat: "<<a<<endl;
}
//拷贝构造
CExample(const CExample& C)
{
a = C.a;
cout<<"copy"<<endl;
}
}
CExample A(10);
CExample B =A或者B(A);//调用了拷贝构造函数
2,赋值函数
CExample & CExample::operator =(const CExample &other)
{
if(this == &other) // (1) 检查自赋值
return *this;
a=other.a;
return *this; // (4)返回本对象的引用
}
CExample A(10);
CExample B ;
B=A;//调用了赋值函数