operator overloading

Can operator overloading be done on structures.
yea it can,
except those subscript and parenthesis overloading. they already have it built in
If it possible then will u please explain me by some example.
First, realize that a "struct" and a "class" are the same thing in C++, the only difference is default visibility ("public, private, protected") - a class is private by default.

Therefore, operator overloading on a structure is the same thing as operator overloading on a class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct Vector {
    Vector()
    : x(0.0), y(0.0) {}
    Vector(double x_comp, double y_comp)
    : x(x_comp), y(y_comp) {}

    double x;
    double y;
};

// Overloads + operator to add each component:
Vector operator+(const Vector& lhs, const Vector& rhs)
{
    return Vector(lhs.x + rhs.x, lhs.y + rhs.y);
}

int main()
{
    Vector a(3, 2);
    Vector b(4, 5);
    Vector c = a + b;
}
Last edited on
Topic archived. No new replies allowed.