The short-hand addition (+=) and subtraction (-=) operators are very commonlyused and thus it would be nice if we overload them in classes. You would beglad to know that there is nothing new or special that needs to be done to achievethis, both the operators are overloaded as usual like other binary operators.
The short-hand operators combine the operation performed by two operators onethe addition or subtraction and the other the assignment. This is all it doesand this is all you need to know!
As nothing new has been introduced so we end the theory here and look at theexample:
// Program to illustrate the
// overloading of shorthand
// operators (+=, -=)
#include
class myclass
{
int a;
int b;
public:
myclass(int,int);
void show();
myclass operator+=(myclass);
myclass operator-=(myclass);
};
myclass::myclass(int x,int y)
{
a=x;
b=y;
};
void myclass::show()
{
cout<}
myclass myclass::operator+=(myclass ob)
{
a+=ob.a;
b+=ob.b;
// note this
return *this;
}
myclass myclass::operator-=(myclass ob)
{
a-=ob.a;
b-=ob.b;
// note this
return *this;
}
void main()
{
myclass ob1(10,20);
myclass ob2(100,200);
ob1+=ob2;
ob1.show();
// even this is possible
// because operator functions
// are retuning *this
ob2=ob1+=ob1;
ob2.show();
}
Related Articles:
Overloadingthe Assignment Operator (=)
OverloadingPost-Fix Forms of ++ and — Operators
OverloadingIncrement/Decrement Operators
Introductionto Operator Overloading in C++ II
Introductionto Operator Overloading in C++
Google search
Wednesday, December 12, 2007
Overloading the Short-Hand Operators (+= and -=)
Posted by
JITENDER KUMAR GARG
at
9:20 PM
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment