简体   繁体   中英

understanding the operator<<() from std::cout

I have written this little code for one of my student coworker, in order to illustrate overloading in c++:

#include <iostream>

int main() {
    std::cout << "Hello World!";
    std::cout.operator<<("Hello World!");
    return 0;
}

I thought naively I will have two times "Hello World.". But the second line send me an adress? I don't understand why ?

According to cppreference (emphasis mine):

Character and character string arguments (eg, of type char or const char*) are handled by the non-member overloads of operator<< . [...] Attempting to output a character string using the member function call syntax will call overload (7) and print the pointer value instead.

So in your case, calling the member operator<< will indeed print the pointer value, since std::cout does not have an overload for const char* .

Instead you can call the free function operator<< like this:

#include <iostream>
int main() {
    std::cout << "Hello World!";           //prints the string
    std::cout.operator<<("Hello World!");  //prints the pointer value
    operator<<(std::cout, "Hello World!"); //prints the string
    return 0;
}

If an operator is a member function then

object operator other_operand

is equivalent to

object.operator(other_operand)

However, if the operator is not a member then it is rather

operator(object,other_operand)

Here you can find the list of overloads of << that are members https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt

And here the list of overloads that are non members https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2

Note that the operator<< for char* is not a member! But there is a member operator<< for void* that can print the value of a pointer of any type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM