有关运算符重载的问题

最帅马老师 最帅马老师 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
#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相同,为什么?
...全文

相关推荐

评论 8
收藏 已收藏
分享
返回顶部
最帅马老师
C++ 语言 65,214 成员 250,514 内容