14、C++复制构造函数和赋值构造函数的代码实例

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值