example1_+operator.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>

class Vector {
private:
    int x, y;
public:
    Vector(int x = 0, int y = 0) : x(x), y(y) {}

    // Overload the + operator
    Vector operator+(const Vector& v) const {
        return Vector(x + v.x, y + v.y);
    }

    // Friend function to overload << operator for output
    friend std::ostream& operator<<(std::ostream& os, const Vector& v) {
        os << "(" << v.x << ", " << v.y << ")";
        return os;
    }
};

int main() {
    Vector v1(3, 4);
    Vector v2(1, 2);
    Vector v3 = v1 + v2;

    std::cout << "v1 = " << v1 << std::endl;
    std::cout << "v2 = " << v2 << std::endl;
    std::cout << "v3 = v1 + v2 = " << v3 << std::endl;

    return 0;
}
Back to operator_overloading