C++中重载复合赋值运算符不会更改变量
Overloading compound-assignment-operator in C++ does not change variable
为了更加熟悉C++,我正在实现一个处理复数的类。
class Complex {
private:
double _real;
double _imag;
public:
Complex();
Complex(double real, double imag);
Complex(const Complex& z);
Complex operator+(const Complex& u) const;
Complex operator+=(const Complex& u);
};
我已经超载了+
运算符,它按预期工作:
Complex Complex::operator+(const Complex& u) const {
Complex z(_real + u._real, _imag + u._imag);
return z;
}
u=1-2i
v=2-1i
u+v=3-3i
此外,我还想过载+=
:
Complex Complex::operator+=(const Complex& u) {
Complex z(_real + u._real, _imag + u._imag);
return z;
}
然而,这并没有如预期的那样工作,并且u+=v
的结果是u=1-2i
。为什么会这样?
您的复合赋值运算符创建一个新对象z,而不是更改原始对象。
在类定义中声明操作符,如
Complex & operator+=(const Complex& u);
并以以下方式定义
Complex & Complex::operator+=(const Complex& u) {
_real += u._real;
_imag += u._imag;
return *this;
}
运算符可以定义为非类友元函数。例如
class Complex {
private:
double _real;
double _imag;
public:
Complex();
Complex(double real, double imag);
Complex(const Complex& z);
Complex operator+(const Complex& u) const;
friend Complex & operator+=(Complex &v, const Complex& u);
};
Complex & operator+=(Complex &v, const Complex& u)
{
v._real += u._real;
v._imag += u._imag;
return v;
}
首先,类赋值运算符应该返回对赋值的引用。
其次,您的代码应该更改当前对象的值。
有两种解决方案:
Complex& Complex::operator+=(const Complex& u) {
*this = Complex(_real + u._real, _imag + u._imag);
return *this;
}
或
Complex& Complex::operator+=(const Complex& u) {
_real += u._real;
_imag += u._imag;
return *this;
}
相关文章:
- 变量没有改变?通过向量的函数调用
- 在向量内更改变量的值不会改变其在向量外的值
- C++11:具有互斥锁的线程看到原子变量的值发生变化,尽管这是唯一可以改变它的代码
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 标准在哪里定义了可变变量可以改变
- C++11:可变的 lambda 似乎没有改变变量?
- printf() 似乎改变了一个变量
- 为什么我的变量在单独的线程中修改时没有改变?C++/boost
- 为什么 Player.x 和 Player.y 变量没有改变?
- C - 如何将各处的静态函数称为改变其私有变量
- 即使"friend class rect"在平方类中被评论,为什么它要改变矩形类的私有变量?
- 为什么调用 CUDA 内核函数时这个类成员变量没有改变
- 全局变量的顺序会改变C /OpenGL的性能
- 为什么一个函数的末尾有常量这个词,即使它确实改变了一个变量
- 如何在C++中改变超类和子类的变量
- setRoomName不会改变变量roomName
- 不能改变变量的值
- 是否有一种方法可以改变变量在内存中的存储方式(位大小)
- Std::cout改变变量的值
- 使用引用改变变量的地址