Answer to Question #327444 in C++ for sohan7

Question #327444

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.

1
Expert's answer
2022-04-11T16:50:23-0400

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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS