为什么ofstream<<重载在作为成员函数调用时会产生不同的结果?

下面是代码:

#include <iostream>
int main()
{
    std::cout << 'a'; // a
    operator << (std::cout, 'a'); // a
    std::cout.operator << ('a'); // 97
}

用命令编译:

g++.exe -Wall -g -Wall -std=c++11  -c <cpp file> -o <o file>
g++.exe <exe file> <o file>  -O0 

aa97执行时产生输出。

似乎由于某种原因调用operator <<重载作为成员函数std::cout调用 的模板特化int,即使我通过了char. 这是正确的吗?

为什么会发生?

回答

没有具有参数的operator<<成员运算符。您可以在此处查看成员列表。在过载被提供作为非成员运算符。您可以在此处查看非会员列表。std::basic_ostreamcharoperator<< charoperator<<(basic_ostream<T>&, char)operator<<

当您同时使用std::cout << 'a'非成员和成员运算符时,会考虑char选择其中的重载。但是当你std::cout.operator<<('a')只使用成员运算符时才考虑。它不得不求助于int过载。


以上是为什么ofstream&lt;&lt;重载在作为成员函数调用时会产生不同的结果?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>