您的位置:首页 > 编程语言 > C语言/C++

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

2013-04-27 19:34 423 查看
#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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐