Thursday, July 9, 2009

What are the different ways to overload an operator in C++?

Using a class declarator


Ex:





Rect Blah {


private:


int x,y;


public:


Rect(int _x, int _y) {x=_x; y=_y;}


int Area(Rect a {


return a.x*a.y;


}


};





Rect operator+ (Rect X, Rect Y) {


int x = X.x+Y.x;


int y = X.y+Y.y;


Rect NewRect = Rect(x,y);


cout%26lt;%26lt;"Area: "%26lt;%26lt;Area(NewRect)%26lt;%26lt;endl;


}

What are the different ways to overload an operator in C++?
The following set of operators is commonly overloaded for user-defined classes:





= (assignment operator)


+ - * (binary arithmetic operators)


+= -= *= (compound assignment operators)


== != (comparison operators)


No comments:

Post a Comment