Search code examples
c++operator-overloadingostream

Operator overload for ostream not working with user defined class


I have this simple program and when i try to cout << 75.0_stC ; i have multiple errors and i don't know why.This things only happen when i pass my temperature object via reference.

class temperature
{
    public:
        long double degrees;
        temperature(long double c): degrees{c}{}
        long double show()const {return degrees;}

};
temperature operator"" _stC(long double t){
    return temperature(t);
}
ostream & operator<<(ostream &ekran, temperature &t)
{
    ekran << t.show();
    return ekran;
}

Solution

  • You likely need to take a const reference to the argument you'd like to print:

    ostream & operator<<(ostream &ekran, const temperature &t)
    

    Temporary won't bind to the non-const reference argument.