Apr 30, 2015 at 9:29am Apr 30, 2015 at 9:29am UTC
Can operator overloading be done on structures.
Apr 30, 2015 at 9:46am Apr 30, 2015 at 9:46am UTC
yea it can,
except those subscript and parenthesis overloading. they already have it built in
Apr 30, 2015 at 11:29am Apr 30, 2015 at 11:29am UTC
If it possible then will u please explain me by some example.
May 1, 2015 at 12:02am May 1, 2015 at 12:02am UTC
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 May 1, 2015 at 12:05am May 1, 2015 at 12:05am UTC