有关运算符重载的问题

最帅马老师 2010-02-23 10:47:07
#include <iostream>
using namespace std;

class son
{
public:
int age;

son():age(0){}

son(int iAge)
{
this->age = iAge;
}

son(const son & rhs)
{
this->age = rhs.age;
}

// Operator
son & operator = ( const son & rhs);
};

son & son::operator =( const son &rhs)
{
if (this == &rhs) return *this;

return *(new son(rhs));
}


void main(void)
{
son s1(10);
son s2;

s2 = s1;

cout << "s1 age is:" << s1.age << endl;
cout << "s2 age is:" << s2.age << endl;

}// main


上例中输出的s2的age是0,但如果在main函数中这样写
son s2 = s1;
则输出的s2的age是10,即与s1相同,为什么?
...全文
117 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
peter_chen_2010 2010-02-23
  • 打赏
  • 举报
回复
楼主例子中调用的是

son & son::operator =( const son &rhs)
{
if (this == &rhs) return *this;

return *(new son(rhs));
}

但在这个重载函数中,LZ并没有对s2.age赋值正确的写法应该是

son & son::operator =( const son &rhs)
{
if (this == &rhs) return *this;
this->age = rhs.age;
return *this;
}


而son s2 = s1调用的是

son(const son & rhs)
{
this->age = rhs.age;
}
ArthurJava 2010-02-23
  • 打赏
  • 举报
回复

this == &rhs;
改为
age == rhs.age;
试试;
debug一下就行了。
ssdx 2010-02-23
  • 打赏
  • 举报
回复
引用 1 楼 pengzhixi 的回复:
son  s2 = s1; //调用的是拷贝构造函数,而非重载的“=”


楼主可以断点,一步步走进去看看。
最帅马老师 2010-02-23
  • 打赏
  • 举报
回复
引用 3 楼 gresume 的回复:
if (this == &rhs) return *this;
有点怀疑这个等号


== 应该没问题,你是觉得哪不对?
GResume 2010-02-23
  • 打赏
  • 举报
回复
if (this == &rhs) return *this;
有点怀疑这个等号
pengzhixi 2010-02-23
  • 打赏
  • 举报
回复
son s2 = s1; //调用的是拷贝构造函数,而非重载的“=”
最帅马老师 2010-02-23
  • 打赏
  • 举报
回复
引用 7 楼 peter_chen_2010 的回复:
楼主例子中调用的是
C/C++ code
son& son::operator=(const son&rhs)
{if (this==&rhs)return*this;return*(new son(rhs));
}
但在这个重载函数中,LZ并没有对s2.age赋值正确的写法应该是
C/C++ code
son& son::operator=(const son&rhs)
{if (this==&rhs)return*this;this->age= rhs.age;return*this;
}

而son s2 = s1调用的是
C/C++ code
son(const son& rhs)
{this->age= rhs.age;
}


正解

64,651

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧