C++复制构造函数和赋值构造函数的代码实例
默认编译器都会自动加上一个,一般都是用常对象作为参数。
测试程序:
class CComplex
{
private:
double real;
double imag;
public:
CComplex(double r,double i);//构造函数
CComplex(const CComplex &com);//复制构造函数
CComplex & operator =(const CComplex & com);//赋值操作符
~CComplex();//析构函数
double getReal() ;
double getImag() ;
};
CComplex::CComplex(double r=1,double i=1):real(r),imag(i)
{
cout<<"调用类的构造函数!"<<endl;
}
double CComplex::getReal() {
return real;
}
double CComplex::getImag()
{
return imag;
}
CComplex::CComplex(const CComplex &com)
{
//com.getReal();常对象引用只能调用常成员函数
real=com.real;
imag=com.imag;
cout<<"调用复制构造函数"<<endl;
}
CComplex & CComplex:: operator =(const CComplex & com)
{
//com.getReal();常对象引用只能调用常成员函数
real=com.real;
imag=com.imag;
cout<<"调用赋值操作函数"<<endl;
return *this;
}
CComplex::~CComplex()
{
cout<<"调用类的析构函数!"<<endl;
}
int main()
{
CComplex com1(1,2);//调用类的构造函数!
cout<<com1.getReal()<<endl;
cout<<com1.getImag()<<endl;
CComplex com2(com1);//调用复制构造函数
CComplex com3;//调用类的构造函数!
com3=com2;//调用赋值操作函数
CComplex com4=com3;//调用复制构造函数
cout<<getRplusI(com4)<<endl;
return 0;
}
程序输出结果:
调用类的构造函数!
1
2
调用复制构造函数
调用类的构造函数!
调用赋值操作函数
调用复制构造函数
调用类的析构函数!
调用类的析构函数!
调用类的析构函数!
调用类的析构函数!
Process returned 0 (0x0) execution time : 0.114 s
Press any key to continue.