C++运算符重载的基本规则和惯用法
大家好!我正在学习C++并尝试理解运算符重载。我写了一个简单的复数类,但遇到了很多问题。这是我的代码:
```cpp
class Complex {
public:
double real, imag;
Complex(double r, double i) : real(r), imag(i) {}
// 重载运算符 +
Complex operator+(Complex other) {
return Complex(real + other.real, imag + other.imag);
}
// 重载运算符 ==
bool operator==(Complex other) {
return (real == other.real && imag == other.imag);
}
};
int main() {
Complex a(3.0, 4.0);
Complex b(1.0, 2.0);
Complex c = a + b; // 可以工作
Complex d = 5.0 + a; // 错误!为什么?
if (c == d) {} // 可以工作,但我听说这是不正确的
return 0;
}
```
问题:
1. 为什么 `5.0 + a` 无法编译,而 `a + 5.0` 可以工作?
2. 我是否正确重载了 `operator+`?什么是“按值返回的惯用法”?
3. 如何正确