#include
using namespace std;
class CString
{
public :
CString(char*str);
CString();
~CString();
void Print();
CString(const CString &src);
CString&operator=(const CString &src);
CString operator+(CString r);
friend ostream&operator<<(ostream &output,CString obj);
private:
char *s;
int length;
};
CString::CString(char*str)
{
length=strlen(str);
s=new char[length];
strcpy(s,str);
}
CString::CString()
{
length=10;
s=new char[length];
s[1]=0;
}
CString::~CString()
{
delete [] s;
}
void CString::Print()
{
cout<<s<<endl;
}
CString::CString(const CString &src)
{
if(strlen(src.s)<length)
{strcpy(s,src.s);}
else
{
int m=strlen(src.s)*2;
char *temp=new char[m];
strcpy(temp,src.s);
delete[]s;
s=temp;
}
}
CString& CString::operator=(const CString &src)
{
if(this==&src)
{return*this;}
else
{
if(strlen(src.s)<length)
{strcpy(s,src.s);}
else
{
int m=strlen(src.s)*2;
char *temp=new char[m];
strcpy(temp,src.s);
delete[]s;
s=temp;
}
}
return *this;
}
CString CString::operator+(CString r)
{
CString tem;
int remain=tem.length-length;
if(remain>strlen(r.s))
{
strcpy(tem.s,s);
strcpy(tem.s,r.s);
return tem;
}
else
{
int m=length+strlen(r.s)+1;
char *temp=new char[m];
strcpy(temp,s);
strcpy(temp,r.s);
delete[]tem.s;
tem.s=temp;
return tem;
}
}
ostream& operator<<(ostream &output,CString obj)
{
output<<obj.s<<endl;
return output;
}
int main()
{
CString str1("str1");
str1.Print();
CString str2("str2");
str2.Print();
CString str3;
str3=str2+str1;
cout<<str3;
CString str4=str3;
cout <<str4;
system("pause");
return 0;
}
编译没有问题,运行就出现问题了,哪里不对,看了半边没找出来