gpt4 book ai didi

c++ operator<<(char) 但在 hexa/int 中

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:25 25 4
gpt4 key购买 nike

为什么三个运算符<<输出方式不同?

#include <iostream>
#include <string>

using namespace std;

int main()
{
operator<<(cout, "Hello").operator<<('w').operator<<(endl); // Hello119

cout << (void *)'w' << endl; // 0x77

cout << 'w'; // w

operator<<(operator<<(cout, "Hello"), 'w').operator<<(endl); // Hellow !!!
}

带有 2 个参数的第一个运算符<<按预期为字符串提供了正确的输出,而其他运算符则没有...

有人可以向我解释一下吗?


更多信息:

cout << "Hello" << 'w' << endl;将被解释为...

operator<<(operator<<(cout, "Hello"), 'w').operator<<(endl); // Hellow

最佳答案

您正在强制转换为 void指针和 std::ostream& operator<<(std::ostream&,void*); 的特化,因此您得到的输出是十六进制值而不是十进制值。

注意:0x77 == 119

另请注意:

您正在调用 std::ostream::operator<<() 成员运算符在这里重载:

   operator<<(cout, "Hello").operator<<('w').operator<<(endl);
// ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
// | |
// | + Calls the std::ostream::operator<<() member operator
// + Calls the std::ostream& operator(std::ostream, T) global overload

char 没有过载, 因此隐式转换为 int取数值119出现在输出中。

来自上述 std::ostream::operator<<() 的链接引用成员函数:

enter image description here正如您在评论中提到的

std::cout << 'w' << 'w' << 'w' << std::endl;    

将推导为全局 std::ostream& operator<<(std:: ostream&, T) 的链式调用过载:

operator<<(operator<<(operator<<(operator<<(std::cout,'w'),'w'),'w'),std::endl);    

关于c++ operator<<(char) 但在 hexa/int 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37054971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com