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

一个赋值运算符重载有关问题的操作有关问题

2012-03-09 
一个赋值运算符重载问题的操作问题程序如下:ErrorMessage.h文件:#ifndefERRORMESSAGE_H#defineERRORMESSAG

一个赋值运算符重载问题的操作问题
程序如下:

ErrorMessage.h文件:

#ifndef   ERRORMESSAGE_H
#define   ERRORMESSAGE_H
class   ErrorMessage{
public:
ErrorMessage(const   char*   pText= "Error ");
~ErrorMessage();
void   resetMessage();
ErrorMessage&   operator=(const   ErrorMessage&   Message);
char*   what()   const{return   pMessage;}
private:
char*   pMessage;
};
#endif


ErrorMessage.cpp文件:

#include   <iostream>
#include   <cstring>
#include   "ErrorMessage.h "
using   std::cout;
using   std::endl;
ErrorMessage::ErrorMessage(const   char*   pText){
pMessage=new   char[strlen(pText)+1];
strcpy(pMessage,pText);
}
ErrorMessage::~ErrorMessage(){
cout < <endl < < "Destructor   called. " < <endl;
delete   []   pMessage;
}
void   ErrorMessage::resetMessage(){
for(char*   temp=pMessage;*temp!= '\0 ';*(temp++)= '* ');
}
ErrorMessage&   ErrorMessage::operator   =(const   ErrorMessage&   message){
if(this==&message)
return   *this;
delete   []   pMessage;
pMessage=new   char[strlen(message.pMessage)+1];
strcpy(this-> pMessage,message.pMessage);
return   *this;
}


main.cpp文件:

#include   <iostream>
#include   <cstring>
using   std::cout;
using   std::endl;
#include   "ErrorMessage.h "
int   main(){
ErrorMessage   warning( "There   is   a   serious   problem   here ");
ErrorMessage   standard;
cout < <endl < < "warning   contains-   " < <warning.what();
cout < <endl < < "standard   contains-   " < <standard.what();
standard=warning;
cout < <endl < < "After   assigning   the   value   of   warning,standard   contains-   "
< <standard.what();
cout < <endl < < "Resetting   warning,not   standard " < <endl;
warning.resetMessage();
cout < <endl < < "warning   now   contains-   " < <warning.what();
cout < <endl < < "standard   now   contains-   " < <standard.what();
cout < <endl;
return   0;
}

在赋值运算符重载函数中,delete   []   pMessage;是删除了哪个的字符数组?如果是左操作数的字符数组,那在赋值时,左操作数和右操作数的地址pMessage是相同的,也就是同一个字符数组啊,即左操作数和右操作数正共用同一个字符数组,删除了不是就没有字符数组了吗?
现在请问在删除之前,左操作数的和右操作数是不是同一个char数组,如果不是,那为什么还要重新删除左操作数char数组后再重新建呢,为什么不能直接使用呢?

[解决办法]
这涉及到深拷贝与浅拷贝问题,若是浅拷贝可以在内存中共享一份拷贝,若是深拷贝就需要先删除原来的数组重新new(细节请参考相关书籍,如Accelerated C++),因为右操作数中的数组可能与左操作数中不同,有可能访问越界。
当然若this==&message,就不能删除了。

热点排行