Of course following code works (it calls std::cout::operator<<):
cout << 1 << '1' << "1" << endl;
Happened to find there is also std::operator<<, and it seems it only works for char or char* arguments:
operator<<(cout, '1'); // ok
operator<<(cout, "1"); // ok
operator<<(cout, 1); // error
So why do we need this operator and how to use it?
Thanks.
We can overload the '>>' and '<<' operators to take input in a linked list and print the element in the linked list in C++. It has the ability to provide the operators with a special meaning for a data type, this ability is known as Operator Overloading.
In C++, a namespace is a collection of related names or identifiers (functions, class, variables) which helps to separate these identifiers from similar identifiers in other namespaces or the global namespace. The identifiers of the C++ standard library are defined in a namespace called std .
You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time. However, this does not mean you cannot use the two namespace in the same program. You can use them each at different times in the same program.
operator<<(cout, '1'); // ok
operator<<(cout, "1"); // ok
operator<<(cout, 1); // error
The first two works because they invoke non-member functions taking two arguments. The functions which takes char
and char const*
as argument are defined as non-member (free) functions.
However, the function which takes int
as argument is defined as member function, which means the third one needs to invoke a member function. If you invoke it as non-member function, then int
would have to be converted into some type for which there exists a non-member function. So when this conversion is considered, it results in ambiguity because there are many possible conversions equally good.
As said, this should work:
cout.operator<<(1); //should work
As to why some functions are defined as members and others as non-members, I don't know the answer. It requires lots of study of the proposals and the decisions that led to this design of the library.
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