简体   繁体   English

从 std::cout 理解 operator<<()

[英]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++:我为我的一位学生同事编写了这个小代码,以说明 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.".我天真地以为我会有两次“Hello World”。 But the second line send me an adress?但是第二行给我一个地址? I don't understand why ?我不明白为什么?

According to cppreference (emphasis mine):根据cppreference (强调我的):

Character and character string arguments (eg, of type char or const char*) are handled by the non-member overloads of operator<< .字符和字符串 arguments(例如,char 或 const char* 类型)由operator<< 的非成员重载处理。 [...] Attempting to output a character string using the member function call syntax will call overload (7) and print the pointer value instead. [...] 使用成员 function 调用语法尝试 output 字符串将调用重载(7)并打印指针值。

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* .因此,在您的情况下,调用成员operator<<确实会打印指针值,因为std::cout没有const char*的重载。

Instead you can call the free function operator<< like this:相反,您可以像这样调用免费的 function operator<<

#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如果操作员是成员 function 则

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在这里您可以找到成员<< ://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这里是非成员的重载列表https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2

Note that the operator<< for char* is not a member!请注意, char*operator<<不是成员! But there is a member operator<< for void* that can print the value of a pointer of any type.但是有一个成员operator<< for void*可以打印任何类型的指针的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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