Search code examples
c++classoperator-overloadingfriend

Overload stream insertion and extraction operator


I'm trying to overload both the stream insertion and extraction operator for my Entrepreneur class.

I've got the following in my Entrepreneur class:

friend istream& Entrepreneur::operator>> (istream &input, Entrepreneur &entrepreneur) {
    cout << "Please enter the item to be sold: ";
    input >> entrepreneur.Item;
    cout << "\nPlease enter the donation amount received: ";
    input >> entrepreneur.Donation;
    cout << "\nPlease enter the amount of members in the group: ";
    input >> entrepreneur.Nr;
    cout << "\nPlease enter the startup amount received: ";
    input >> entrepreneur.StartupAmt;
    cout << endl;
    return input;
}

friend ostream& Entrepreneur::operator<< (ostream &output, Entrepreneur &entrepreneur) {
    output << "Item: " << entrepreneur.Item << endl;
    output << "Members in group: " << entrepreneur.Nr << endl;
    output << "Startup amount: " << entrepreneur.StartupAmt << endl;
    output << "Donation amount: " << entrepreneur.Donation << endl;
    output << "Expenses: " << entrepreneur.Expenses << endl;
    output << "Points earned: " << entrepreneur.Points << endl;
    output << "All items sold: " << entrepreneur.Sold ? "Yes" : "No" << endl;
    return output;
}

In my main.cpp file, I'm trying the following code:

int main() {
    Entrepreneur Group3;
    cin >> Group3;
}

The code is unable to compile. I'm getting the following error message:

Binary Operator '>>' can't be applied to the expression of type 'istream' and 'Entrepreneur'

Can you guys please help me to figure out what is wrong with the above code?


Solution

  • The signatures are wrong. You're using friend, because you want to declare/define non-member functions. Drop the Enterpreneur:: and the problem is solved.

    The class' definition should look something like:

    class Enterpreneur
    {
    public:
        ...
    
        friend istream& operator>> (istream &input, Entrepreneur &entrepreneur);
        friend ostream& operator<< (ostream &output, Entrepreneur const& entrepreneur);
        //                                                        ^^^^^
        //                                    we're not modifying the argument, are we?
    };
    

    and then just define those operators as any other non-member function (no friend keyword), or define them inline with the class.