I get how this operator overloading works here in this code.....
class operatorOver {
public:
int a, b, c;
};
operatorOver operator+(const operatorOver &a, const operatorOver &b) {
operatorOver aa;
aa.a = b.a + a.a;
return aa;
}
int main()
{
operatorOver aaa, bbb, ccc;
aaa.a = 100;
bbb.a = 200;
ccc = aaa + bbb;
cout << ccc.a << endl;
system("pause");
};
but this version I don't understand how this one works here....
class operatorOver {
public:
operatorOver operator+(const operatorOver &a) {
operatorOver aa;
aa.a = (*this).a + a.a;
return aa;
}
int a, b, c;
};
int main()
{
operatorOver aaa, bbb, ccc;
aaa.a = 100;
bbb.a = 200;
ccc = aaa + bbb;
cout << ccc.a << endl;
system("pause");
};
the 1st one I showed, I'm assuming the code of the operator overloading here is taking into 2 object classes in order for it to work...
but how come the 2nd example it's showing that I don't need to create another object class in it's parameters but still work... when you look in main() you see that there are 2 object classes still being passed in.... I'm lost.
Some of the binary operators, such as +, can be overloaded as member functions as well as non-member functions.
When + is overloaded as a member function, the function needs to be declared with one argument. When the operator is used as:
a + b
the call is resolved as
a.operator+(b);
When it is overloaded as a non-member function, the function needs to be declared with two arguments. When the operator is used as:
a + b
the call is resolved as
operator+(a, b);
Further reading: http://en.cppreference.com/w/cpp/language/operators
In the second example, two object are passed. There's a and there is also this. The object passed as this is the left side of the operation.
Also note that your member operator+ should be const, since it doesn't mutate any data members of this.
Your member operator also invoke undefined behavior, since you are using a unassigned value:
// The member function
operatorOver operator+(const operatorOver &a) {
operatorOver aa;
// What is the value of aa.a? Undefined behavior!
aa.a = aa.a + a.a;
return aa;
}
To be equivalent to you non-member function, it should be this implementation:
// The member function
operatorOver operator+(const operatorOver &a) const {
operatorOver aa;
// Member `a`, could be written `this->a`
aa.a = a + a.a;
return aa;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With