Overloading the Unary Operators in C++

The unary + and – operators can be overloaded.

The + and – are unary operators. They can be overloaded, too. Since the unary operator operates on one operand that is the calling object itself, the unary function operator has no parameters.

Here is an example that overloads the – operator. Add the function header in Listing 14.1, Rational.h.

Rational operator-()

Implement the function in Listing 14.3, Rational.cpp.

1 Rational Rational::operator-()
2 {
3   
return Rational(-numerator, denominator);
4 }

Negating a Rational object is the same as negating its numerator (line 3). Line 4 returns the calling object. Note that the negating operator returns a new Rational. The calling object itself is not changed.

The following code

1 Rational r2(2, 3);
2 Rational r3 = -r2;
// Negate r2
3 cout << “r2 is ” << r2.toString() << endl;
4 cout <<
“r3 is ” << r3.toString() << endl;

displays

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *