I have simple lines of code, where I am using insertion operator <<
to show hello world string. If I use a operator b then it should result to a.operator(b);
I try to do same thing with insertion operator and in output I got address of string, rather than actual string.
std::cout<<"Hello world"<<std::endl;
std::cout.operator<<("Hello world").operator<<(std::endl);
Output:
Hello world
0120CC74
I am using Visual Studio.
Does my operator conversion has any problem?
The insertion ( << ) operator, which is preprogrammed for all standard C++ data types, sends bytes to an output stream object. Insertion operators work with predefined "manipulators," which are elements that change the default format of integer arguments.
In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.
To get cout to accept a Date object after the insertion operator, overload the insertion operator to recognize an ostream object on the left and a Date on the right. The overloaded << operator function must then be declared as a friend of class Date so it can access the private data within a Date object.
std::cout<<"Hello world"<<std::endl;
use overloaded output operator for const char*
, that is free function, not member function.
std::cout.operator<<("Hello world").operator<<(std::endl);
use overloaded output operator for const void*
, since const char*
is implicitly convertible to const void*
.
You can look at member overloads here and free overloads here
My bet is that member function operator for std::ostream(char*)
is not overloaded.
If you look at ostream::operator<<, void*
is best match and char*
naturally gets converted to it, while global operator<<(std::basic_ostream), has exact overloads for char*
types, which gets picked up.
Of course, they behave differently.
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