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.
Both unary and binary operators are functions with special names. So they may be overloaded as all other functions. The only difference is that they require a definite number of parameters one for a unary operator and two for a binary operator. In this case, the operators are defined as the member of a class, the number of their parameters reduced by one, so a unary operator gets no parameter, and a binary operator gets one.
#include <iostream>
using namespace std;
class Counter {
public:
Conter(int x) : count(0), limit(x)
{}
void operator++() {
count++;
}
bool operator!() {
return count >= limit;
}
int get() {
return count;
}
private:
int count;
int limit;
};
int main() {
for (Counter couner(10); !counter; ++counter) {
cout << counter.get() << endl;
}
return 0;
}
Comments
Leave a comment