1、C++关于拷贝构造函数和赋值运算符重载问题的测试程序。因为调用顺序不清,导致内存泄漏new delete

#include <iostream>
#include <cstring>
using namespace std;
class ClsComplex
{
private:
    int m_nReal;
    int m_nImag;
    char *m_p_chStr;
public :
    ClsComplex(int real=0,int imag=0,char *str=" ");
    //复制构造函数重载(常中引不会修改其值)
    ClsComplex(const ClsComplex &);
    //赋值运算符的重载
    ClsComplex  operator =(const ClsComplex & c);//如果返回类不是引用,则会自动调用拷贝构造函数
    ~ClsComplex()
    {
        delete m_p_chStr;
    }

};
ClsComplex::ClsComplex(int real,int imag,char *str):m_nReal(real),m_nImag(imag)
{
    m_p_chStr=new char[strlen(str)+1];
    strcpy(m_p_chStr,str);    
}
//拷贝构造函数
ClsComplex::ClsComplex(const ClsComplex & com)
{
    //因为构造函数是初始化对象第一个进来的,所以
    cout<<"Copy Constructor is Called! "<<endl;
    m_nReal=com.m_nReal;
    m_nImag=com.m_nImag;
    //重新分配,(删除本对象的地址)
    m_p_chStr=new char[strlen(com.m_p_chStr)+1];
    strcpy(m_p_chStr,com.m_p_chStr);
}
ClsComplex  ClsComplex::operator=(const ClsComplex & com)
{
    cout<<"Overload operator = is Called! "<<endl;    
    //因为这个函数只有在不是初始化那个时刻才调用的  如:complex a,b(1,2,"3"); a=b;//调用这个函数 complex b(1,2,"3"); complex a=b;调用拷贝构造函数 其它返回类对象时均调用 拷贝构造函数,所以一般这两者同时存在
    if(this==&com) return *this;
    m_nReal=com.m_nReal;
    m_nImag=com.m_nImag;
    delete m_p_chStr;//重新分配,删除本对象的地址
    m_p_chStr=new char[strlen(com.m_p_chStr)+1];
    strcpy(m_p_chStr,com.m_p_chStr);
    return *this;
    
}

int main()
{
    //delete 删除时必须之前用过new或者会发生内存泄漏,报错
    ClsComplex com1(1,2,"测试");
    ClsComplex com2;
    //ClsComplex com2=com1;//直接调用拷贝构造函数,不调用普通构造函数
    com2=com1;//没有operator =重载赋值运算符函数,则调用拷贝构造函数
//测试new delete是否出错
   // char *a="测试";
   // char *p=new char[strlen(a)+1];
   // strcpy(p,a);
   // delete p;
    return 0;
}

程序运行结果:
Overload operator = is Called!
Copy Constructor is Called!

Process returned 0 (0x0)   execution time : 0.886 s
Press any key to continue.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值