Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't 'operator<<(cout, double)' work?

I'm studying overloaded operators. I don't get the difference between using the <<-operator on a double / an std::string.

int main()
{
    double a = 12;
    string s = "example";

    operator<<(cout, a); //doesn't work
    cout.operator<<(a);  //works

    operator<<(cout, s); //works
    cout.operator<<(s);  //doesn't work   
}    

Why aren't operator<<(cout, a) and cout.operator<<(s); working?

like image 232
Gabonica Avatar asked Dec 07 '22 11:12

Gabonica


1 Answers

Because that operator is defined as a member function, not as a free function.

Operators can be overloaded in those two ways, which when used with regular operator syntax will be transparent to the user. However, when using explicit syntax, you have to use the one specific to the actual function definition.

This example shows the difference in practice:

class Stream {
    Stream& operator<<(Inside);
};

Stream& operator<<(Stream&, Outside);

For std::string, Outside way is used. For double, Inside is.

like image 134
Bartek Banachewicz Avatar answered Dec 29 '22 01:12

Bartek Banachewicz