Question: Insertion operator not producing the expected output?


Insertion operator not producing the expected output?

Answers 2
Added at 2017-01-01 10:01

Here is the code

using namespace std;
    cout<<"Hellow World"<<endl;
    cout.operator<<("Hellow World");

I know that cout<<"Hellow World"<<endl; is interpreted as cout.operator<<("Hellow World"); But this code is producing the following results

Hellow World


if i use operator<<(cout,"Hellow World"); works fine what is the difference between cout.operator<<("Hellow World"); and operator<<(cout,"Hellow World");

nr: #1 dodano: 2017-01-01 10:01

std::basic_ostream overloads operator<< in two groups, members and non-members.

The difference is due to the fact that when you write cout<<"Hellow World"<<endl; the non-member overload of const char* is chosen to print the string literal.

When you call the member version, the best fit is only the void* overload.

nr: #2 dodano: 2017-01-01 15:01

what is the difference between cout.operator<<("Hellow World"); and operator<<(cout, "Hellow World");

When you write cout.operator<<("Hellow World"); you are calling the operator<< method and passing a const char *. Because this method is not overloaded to take a const char *, but is overloaded to take a const void *, that's the one you call and get 0x8048830 (which is the address of the 'H' character in your string).

When you write operator<<(cout, "Hellow World") you are calling a free function operator<< that takes an output stream on the left-hand side and a const char * on the right-hand side. There happens to exist such a function, and it has the following declaration (simplified):

std::ostream& operator<<(std::ostream& os, const char *s);

And so you get printed the sequence of characters that begin at s, and end at the first '\0' that is encountered (so you get Hellow, world).

Finally, when you write std::cout << "Hello, world" << std::endl;, since you are passing a const char * to operator<<, the free function, being a perfect match, is chosen over the method operator<<.

Source Show
◀ Wstecz