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

返回值和返回引用的有关问题

2012-02-23 
返回值和返回引用的问题String的赋值函数operate的实现如下:String&String::operate(constString&other)

返回值和返回引用的问题
String的赋值函数operate   =   的实现如下:
String   &   String::operate=(const   String   &other)
{
if   (this   ==   &other)
return   *this;
delete   m_data;
m_data   =   new   char[strlen(other.data)+1];
strcpy(m_data,   other.data);
return   *this;//   返回的是   *this的引用,无需拷贝过程
}
如果采用的是返回值,实现方式如下:

String   String::operate=(const   String   &other)
{
if   (this   ==   &other)
return   *this;
delete   m_data;
m_data   =   new   char[strlen(other.data)+1];
strcpy(m_data,   other.data);
return   *this;//   返回的是   *this的引用,无需拷贝过程
}

String   a;
String   b;
a   =   b;  
为什么采用返回值的形式会调用拷贝构造函数呢?我觉得不需要调用就可以了啊?
因为a=b实际上就是a.operator=(b),返回值对它来说没有用处,即使没有返回值
使用如下方式:
void   String::operator   =(   const   String   &other   )
{
if   (this   ==   &other   )
return   ;

delete   []   m_data;

int   length   =   strlen(   other.m_data   );
m_data   =   new   char[   length+1   ];
strcpy(   m_data,   other.m_data   );
return   ;
}
a=b也一样可以完成赋值操作啊.为什么返回值是值的形式会自动调用拷贝构造函数呢?

[解决办法]
因为是规定!
返回“值”就需要创建一个临时对象来保存这个值。

热点排行