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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With