Explain how overloading a unary operator is almost similar to overloading a binary operator with necessary examples and include main() function to demonstrate. Mention the differences between these two in terms of number of operands they deal with.
A unary as its name implies requires only one argument, while a binary operator requires two operands.
This is true if the operators are overloaded as external functions (operator!(), and operator<<() in my example), but if the operator is a member of the class the first operand is implicit and should not appear on the parameter list (as for operator++(), and operator+() in my example)
.#include <iostream>
using namespace std;
class Integer {
int value;
public:
Integer(int v=0) : value(v)
{}
Integer operator+(Integer& other) {
return Integer(value + other.value);
}
Integer& operator++() {
value++;
return *this;
}
void print(ostream& os) {
os << value;
}
friend bool operator!(const Integer&);
};
ostream& operator<<(ostream& os, Integer& i) {
i.print(os);
return os;
}
bool operator!(const Integer& I) {
return I.value != 0;
}
int main() {
Integer I(10), J(20);
cout << I << " + " << J << " = " << I+J << endl;
cout << "++I " << ++I << endl;
if (!I) {
cout << "I is not zero" << endl;
}
else {
cout << "I is zero" << endl;
}
return 0;
}
Comments
Leave a comment