运算符重载的问题~~
#include <iostream.h>
#include <string.h>
#include "mystr.h"
mystr::mystr() //调用无参构造函数
{
len=0;
p=NULL;
}
mystr::mystr(char *s) //调用有参构造函数
{
len=strlen(s);
if(!len) p=NULL;
else p=new char[len+1];
strcpy(p,s);
}
mystr::mystr(const mystr&a) //调用拷贝构造函数
{
len=a.len;
p=new char[a.len+1];
strcpy(p,a.p);
}
mystr::~mystr()
{
if(p) delete[]p;
}
mystr mystr::operator = (char *aa)
{
if(p) delete[]p;
p=new char[strlen(aa)+1];
strcpy(p,aa);
len=strlen(aa);
return *this;
}
mystr mystr::operator =(mystr&a2)
{
if(p) delete[]p;
p=new char[strlen(a2.p)+1];
strcpy(p,a2.p);
len=a2.len;
return *this;
}
mystr mystr::operator +(mystr&a3)
{
mystr b;
if(b.p) delete[] b.p;
b.p=new char[strlen(p)+strlen(a3.p)+1];
strcpy(b.p,p);
strcat(b.p,a3.p);
return b;
}
ostream& operator<<(ostream&output,mystr&a5)
{
output<<a5.p;
return output;
}
istream& operator>>(istream&in,mystr&a4)
{
char ss[100];
in>>ss;
a4=ss; //a4.p=ss;
return in;
}
重载>>的函数里 a4=ss; 为什么不能写成a4.p=ss;????
[最优解释]
a4=ss;
a4.p=ss;
istream& operator>>(istream&in,mystr&a4)
{
char ss[100];
in>>ss;
a4=ss; //a4.p=ss;
return in;
}