+ 1
What is the benefit of operator overloading..?
4 Antworten
+ 1
It is a syntactic suger.
Imagine that you created a class like this:
// Code #1
class INT{
int x;
public:
~INT(){}
INT(int y):x(y){}
INT(INT const&t):x(t.x){}
INT(INT&&t):x(t.x){}
INT& operator= (int y){x=y;return*this;}
INT& operator= (INT const&t){x=t.x;return*this;}
INT& operator= (INT&&t){x=t.x;return*this;}
INT& setValue (int y){x=y;return*this;}
INT& setValue (INT const&t){x=t.x;return*this;}
INT& setValue (INT&&t){x=t.x;return*this;}
} a, b, c, d;
// Text
And, you create four objects named a, b, c and d.
Then, you want to set them all to 28, which way would you choose?
// Code #2
a=b=c=d=28;
// Code #3
a.setValue(b.setValue(c.setValue(d.setValue(28))));
0
do you know any way to add objects directly like any number?
operator overloading will do that work.
0
It allows UDTs (User Defined Types) to act like build-in types.
So, similar to the way you can do:
int x=1, y=2, z;
z = x + y;
.. for build-in types you can do:
class A{..} ;
A a, b, c;
c = b + a;
The way this is achieved is to use operator overloading.