C++赋值运算符重载的有关问题
C++赋值运算符重载的问题
为什么我写的赋值运算符重载函数没有被调用,我调试A b=a; 这个时进不了A& operator = (const A &rh)函数,好像是被默认的构造函数替代了,两个print输出来的都是1 ,请问要怎么修改 ?
------解决方案--------------------
A b=a;
调用的是拷贝构造函数 A(const A& rhs), 不是 operator =
------解决方案--------------------
楼上说的对,可以改成
A b(1);
b = a;
------解决方案--------------------
创建一个新对象的时候用构造函数.
改变已有的对象的时候用赋值运算符
为什么我写的赋值运算符重载函数没有被调用,我调试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;
------解决方案--------------------
创建一个新对象的时候用构造函数.
改变已有的对象的时候用赋值运算符