xxxxxxxxxx
class Vector {
public:
Vector(int x, int y) : x_(x), y_(y) {}
int x() const { return x_; }
int y() const { return y_; }
friend Vector operator+(const Vector& v1, const Vector& v2);
private:
int x_, y_;
};
Vector operator+(const Vector& v1, const Vector& v2) {
return Vector(v1.x() + v2.x(), v1.y() + v2.y());
}
int main() {
Vector a(1, 2), b(3, 4);
Vector c = a + b;
return 0;
}
In the main function, two Vector objects are created (a and b), and then added together using the + operator. The result is assigned to a third Vector object c.
By using friend functions to overload operators in C++, you can provide convenient and natural syntax for working with user-defined types in C++, and enable expressions like a + b to be evaluated just like built-in types.