NodeJS
NodeJS

Reputation: 132

no operator "<<" matches these operands when using operator overloading

Error ocurred with the following try to operator overloading:

#include<iostream>
#include<string>
#include<ostream>
using namespace std;

class Dollar
{
private:
    float currency, mktrate, offrate;
public:
    Dollar(float);
    float getDollar() const;
    float getMarketSoums() const;
    float getofficialSoums() const;
    void getRates();

    // In the following function I was trying to overload "<<" in order to print all the data members:
    friend void operator<<(Dollar &dol, ostream &out)
    {
        out << dol.getDollar() << endl;
        out << dol.getMarketSoums() << endl;
        out << dol.getofficialSoums() << endl;
    }
};

Dollar::Dollar(float d)
{
    currency = d;
}

float Dollar::getDollar() const
{
    return currency;
}

float Dollar::getMarketSoums() const
{
    return mktrate;
}

float Dollar::getofficialSoums() const
{
    return offrate;
}

void Dollar::getRates()
{
    cin >> mktrate;
    cin >> offrate;
}

int main()
{
    Dollar dollar(100);
    dollar.getRates();

    // In this line I am getting the error. Could you please help to modify it correctly?
    cout << dollar;

    system("pause");
    return 0;
}

Upvotes: 0

Views: 2075

Answers (1)

Raindrop7
Raindrop7

Reputation: 3911

You have to pass std::ostream object as the first parameter to the insertion operator << not as the second one as long as you are calling it that way:

friend void operator << (ostream &out, Dollar &dol);
  • You should make the object passed in to the insertion operator constant reference as long as this function is only prints and not intending to modify the object's members:

    friend void operator << (ostream &out, const Dollar& dol);
    
  • So pass by reference to avoid multiple copies and const to avoid unintentional modification.

  • If you want to invoke to get it work the way you wanted you can do this:

    friend void operator<<(const Dollar &dol, ostream &out){
        out << dol.getDollar() << endl;
        out << dol.getMarketSoums() << endl;
        out << dol.getofficialSoums() << endl;
    }
    

And in main for example:

    operator << (dollar, cout); // this is ok
    dollar << cout; // or this. also ok.

As you can see I reversed the order of calling the insertion operator to match the signature above. But I don't recommend this, it is just to understand more how it should work.

Upvotes: 4

Related Questions