局部指针变量指向堆空间的释放问题
#include<iostream.h>
#include<string.h>
//using namespace std;
class String
{
public:
String(const char* s="")
{
if(s==NULL)
str=NULL;
else
{
str=new char[(strlen(s)+1)];
strcpy(str,s);
}
}
String(const String& s)
{
if(s.str==NULL)
str=NULL;
else
{
str=new char[(strlen(s.str)+1)];
strcpy(str,s.str);
}
}
String& operator=(const String& s)
{
if(this!=&s)
{
delete []str;
str=new char[strlen(s.str)+1];
for(int i=0;i<=strlen(s.str);i++)
{
str[i]=s.str[i];
}
}
return *this;
}
bool operator==(const String& s)
{
if(this==&s)
return true;
else
{
if(strlen(str)!=strlen(s.str))
return false;
else
{
for(int i=0;i<strlen(str);i++)
{
if(str[i]!=s.str[i])
return false;
}
return true;
}
}
}
String operator+(String& s)
{
int t=0;
String p;
p.str=new char[strlen(str)+strlen(s.str)+1];
strcpy(p.str,str);
for(long i=strlen(str);i<=(strlen(str)+strlen(s.str));i++)
{
p.str[i]=s.str[t];
t++;
}
return p;
}
char& operator[](int i){return str[i];}
const char& operator[](int i)const{return str[i];}
~String(){delete []str;}
friend istream& operator>>(istream& in,String& s);
friend ostream& operator<<(ostream& out,const String& s);
private:
char* str;
};
istream& operator>>(istream& in,String& s)
{
char s0[100];
in>>s0;
s.str=new char[strlen(s0)+1];
strcpy(s.str,s0);
return in;
}
ostream& operator<<(ostream& out,const String& s)
{
cout<<s.str;
cout<<endl;
return out;
}
int main()
{
String s1;
cout<<"enter s1:";
cin>>s1;
String s2;
cout<<"enter s2:";
cin>>s2;
cout<<"s1+s2="<<(s1+s2);
String s3(s1);
if(s1==s3){cout<<"s1=s3"<<endl;}
s3=s2;
cout<<s3;
s3[0]='p';
cout<<s3;
return 0;
}