【发布时间】:2014-09-05 20:02:39
【问题描述】:
我正在努力学习C++。而且我有一些运算符重载函数,如下所示(我取自 The C++ Programming Language 第 76 页,第 76 页):
complex& operator+=(complex z) { re += z.re; im += z.im; return *this; } // add to re and im
// and return the result
complex& operator−=(complex z) { re -= z.re; im -= z.im; return *this; }
complex& operator*=(complex); // defined out-of-class somewhere
complex& operator/=(complex); // defined out-of-class somewhere
+= 重载工作正常,但对于 -=,我得到 10 编译器错误:
如果我删除 = 并重载 - 运算符,它会编译。是什么原因 ?我想知道我做错了什么?我尝试了几种组合,清除 - 重建解决方案,重新启动 Visual Studio,但它们不起作用。
注意:我使用的是 Visual Studio 2013,并且我已经安装了 Visual C++ Compiler November 2013 CTP
这是完整的类定义:
class complex{
double re, im;
// representation: two doubles
public:
complex(double r, double i) :re{ r }, im{ i } {} // construct complex from two scalars
complex(double r) :re{ r }, im{ 0 } {} // construct complex from one scalar
complex() :re{ 0 }, im{ 0 } {} // default complex: {0,0}
double real() const { return re; }
void real(double d) { re = d; }
double imag() const { return im; }
void imag(double d) { im = d; }
complex& operator+=(complex z) { re += z.re; im += z.im; return *this; } // add to re and im
// and return the result
complex& operator−=(complex z) { re -= z.re; im -= z.im; return *this; }
complex& operator*=(complex); // defined out-of-class somewhere
complex& operator/=(complex); // defined out-of-class somewhere
};
【问题讨论】:
-
附带说明,最好让您的操作员使用
const complex&。就像现在一样,当您调用操作员时,正在复制给定的复合体,这是一种浪费。
标签: c++ visual-studio operator-overloading