#include <iostream.h>
#include <string.h>
class String
{
private:
char *str;
public:
String(char *s="")
{
int size =strlen(s);
str=new char[size+1];
strcpy(str,s);
}
String(String & ss)
{
str=new char [strlen(ss.str)+1];
strcpy(str,ss.str);
} ~String()
{
delete str;
} void showString()
{
cout << "字符串变量为=" <<str << endl;
}
String & operator=(String & ss)
{
if(this==&ss)
{
return *this;
}
else
{
cout << "赋值运算符" << endl ;
delete str;//这个好像也可以不要???
str= new char[strlen(ss.str)+1];
strcpy(str,ss.str );
return *this;
}
}
String operator + (String s2)
{
String temp;
temp.str =new char[strlen(str)+strlen(s2.str)+1];//没有对应的delete???
strcpy(temp.str,str);
strcat(temp.str,s2.str);
return(temp);
}
};
void main()
{
String s1("字符串1");
cout  << "s1=";
s1.showString (); String s2(s1);
cout << "s2 = ";
s2.showString (); String s3=s1+s2;
s3.showString(); s3=s3+s1;
s3.showString (); s2=s3+"fff";
s2.showString();

}

解决方案 »

  1.   

    operator=中要,不然内存泄漏
    operator+中可以不要,destruct时delete
      

  2.   

    谢谢 ndy_w
    strcat(temp.str,s2.str);问一下,为什么可以访问私有成员??我没有定义友元??
      

  3.   

    String operator + (String s2) 
    {
    strcat(temp.str,s2.str);
    }访问自己类中的私有成员当然可以
      

  4.   

    >> 但是好像没问题 
    你把delete全部注掉都不会有报错,VC没办法检测堆内存的。
      

  5.   

    析构中 需要释放数组 delete[]