[求助] 简单代友引发的错误
#include<iostream.h>#include<string.h>
class Cstring
{
private:
char *m_str;
public:
Cstring();
Cstring(char *string);
//重载+
Cstring operator+(const Cstring &other);
//重载<<
friend void operator<<(ostream &stream,const Cstring &str);
//重载=
Cstring &operator=(const Cstring &other);
//析构函数
~Cstring();
};
Cstring::Cstring()
{
m_str=NULL;
}
//普通构造函数
Cstring::Cstring(char *string)
{
if(string==NULL)
{
m_str=new char[1];
*m_str='\0';
}
else
{
m_str=new char[strlen(string)+1];
strcpy(m_str,string);
}
}
//重载加号
Cstring Cstring::operator +(const Cstring &other)
{
Cstring temp;
temp.m_str=new char[strlen(m_str)+strlen(other.m_str)+1];
strcpy(temp.m_str,m_str);
strcat(temp.m_str,other.m_str);
return temp;
}
//重载<<运算符
void operator<<(ostream &stream,const Cstring &str)
{
stream<<str.m_str<<endl;
}
//析构函数
Cstring::~Cstring()
{
if(m_str)
delete [] m_str;
m_str=NULL;
}
//重载运算符=
Cstring &Cstring::operator =(const Cstring &other)
{
if(this==&other)
return *this;
if(m_str)
delete []m_str;
m_str=new char[strlen(other.m_str)+1];
strcpy(m_str,other.m_str);
return *this;
}
//主函数
int main()
{
Cstring string1("Hello"),string2("every one!");
Cstring string3;
cout<<string1;
cout<<string2;
string3=string1+string2;
cout<<string3;
return 0;
}
//为什么我把析构函数删除了可以正常运行,不删除的话就出现错误