Answer to Question #327440 in C++ for sohan

Question #327440

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:25-0400

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

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