C++ Unary Operator Overloading
C++ Operator Overloading and Function Overloading
Unary operators operate on only one operand. The following are examples of unary operators:
- Increment operator ( ++ ) and decrement operator ( -- )
- Unary minus operator, i.e., the minus sign ( - )
- The logical NOT operator ( ! )
Unary operators usually appear to the left of the objects they operate on, such as !obj, -obj, and ++obj, but sometimes they can also be used as postfix, such as obj++ or obj--.
The following example demonstrates how to overload the unary minus operator ( - ).
Example
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinity
int inches; // 0 to 12
public:
// Required constructor
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// Method to display distance
void displayDistance()
{
cout << "F: " << feet << " I:" << inches <<endl;
}
// Overload the unary minus operator ( - )
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1; // Take the negative
D1.displayDistance(); // Distance D1
-D2; // Take the negative
D2.displayDistance(); // Distance D2
return 0;
}
When the above code is compiled and executed, it produces the following results:
F: -11 I:-10 F: 5 I:-11
I hope the above example can help you better understand the concept of unary operator overloading. Similarly, you can try overloading the logical NOT operator ( ! ).
other extensions