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

C++赋值运算符重载的有关问题

2013-07-04 
C++赋值运算符重载的问题为什么我写的赋值运算符重载函数没有被调用,我调试A ba 这个时进不了A& operato

C++赋值运算符重载的问题
为什么我写的赋值运算符重载函数没有被调用,我调试A b=a; 这个时进不了A& operator = (const A &rh)函数,好像是被默认的构造函数替代了,两个print输出来的都是1 ,请问要怎么修改 ?


#include<iostream>
#include<string>
#include<vector>

using namespace std;

class A
{
public:
A(int x)
{
ix = x;
}

A& operator = (const A &rh)
{
 if (this == &rh)
 {
 return *this;
 }
 
 ix = rh.ix + 1;
return *this;

}

void print()
{
cout << ix << endl;
}
private:
int ix;
};

int main()
{
A a(1);
A b=a;
a.print();
b.print();
}

[解决办法]
A b=a; 
调用的是拷贝构造函数 A(const A& rhs), 不是 operator = 
[解决办法]
楼上说的对,可以改成
A b(1);
b = a;
[解决办法]
创建一个新对象的时候用构造函数.
改变已有的对象的时候用赋值运算符

热点排行