首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

运算符重载的有关问题~

2012-12-14 
运算符重载的问题~~#include iostream.h#include string.h#include mystr.hmystr::mystr()//调用无

运算符重载的问题~~
#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就指向了一个无效的内存地址。

[其他解释]
引用:
C/C++ code??1    a4=ss;

调用的是重载的复制运算符函数:mystr mystr::operator =(mystr&amp;a2)。
在这个函数里为p开辟了内存空间并使用了字符串拷贝函数。

C/C++ code??1    a4.p=ss;
只是简单的把ss的地址赋给了p,p指向了一个局部变量的内存地址。
当函数
C/C++ co……


谢谢了~~

热点排行