运算符重载的问题~~
#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;
调用的是重载的复制运算符函数:mystr mystr::operator =(mystr&a2)。
在这个函数里为p开辟了内存空间并使用了字符串拷贝函数。
a4.p=ss;
只是简单的把ss的地址赋给了p,p指向了一个局部变量的内存地址。
当函数
istream& operator>>(istream&in,mystr&a4)
{
char ss[100];
in>>ss;
a4=ss; //a4.p=ss;
return in;
}
执行完以后,ss的空间被回收,p就指向了一个无效的内存地址。
[其他解释]
谢谢了~~