Avatar ·

Basic rules and idioms of operator overloading in C++

Hello everyone! I've been studying C++ for about six months, and I'm confused about operator overloading. I think I understand the syntax, but I keep running into problems.\n\nFor example, I tried to write a simple Vector2D class for 2D vectors with operator+ overloading. Here's my code:\n\n```cpp\nclass Vector2D {\npublic:\n Vector2D(double x, double y) : x_(x), y_(y) {}\n \n Vector2D operator+(const Vector2D& other) {\n return Vector2D(x_ + other.x_, y_ + other.y_);\n }\n \n // Problem: why can't I write 2.0 + v?\n // Or v1 + v2 + v3?\n \nprivate:\n double x_, y_;\n};\n```\n\nWhen I try to use `Vector2D v3 = 2.0 + v1;`, the compiler complains. Also, I'm not sure how to properly overload the `<<` operator for output to cout, and when I need to return