Avatar ·

C++ 运算符重载的基本规则和惯用法

大家好!我学习 C++ 大约半年了,对运算符重载有些困惑。我似乎理解语法,但总是遇到问题。 例如,我尝试为二维向量编写一个简单的 Vector2D 类,并重载 + 运算符。这是我的代码: ```cpp class Vector2D { public: Vector2D(double x, double y) : x_(x), y_(y) {} Vector2D operator+(const Vector2D& other) { return Vector2D(x_ + other.x_, y_ + other.y_); } // 问题:为什么我不能写 2.0 + v? // 或者 v1 + v2 + v3? private: double x_, y_; }; ``` 当我尝试使用 `Vector2D v3 = 2.0 + v1;` 时,编译器报错。我也不确定如何正确重载 `<<` 运算符用于 cout 输出,以及何时需要返回引用,何时返回值。 能否提供运算符重载的基本规则和惯用法总结?哪些运算符可以重载,哪些不能?何时需要 friend 函数?以及如何使