为什么当作为成员函数调用时 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_ostream 没有 char 成员运算符。您可以看到成员operator<< here 的列表。 char 重载作为非成员运算符 operator<<(basic_ostream<T>&,char) 提供。您可以看到非会员列表operator<< here

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

,

类模板 std::basic_ostream 具有以下成员运算符

basic_ostream<charT,traits>& operator<<(int n);

但它没有 char 类型的成员。

对于类型 char 有一个非成员模板函数

template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>&,char);

因此,当您使用成员函数时,由于整数提升,char 类型的参数被提升为 int 类型

std::cout.operator << ('a');

但是在这次通话中

operator << (std::cout,'a');

使用非成员模板函数

,

似乎出于某种原因调用 operator << 重载作为 std::cout 的成员函数会调用 int 的模板特化,即使我传递了 char。对吗?

是的。

为什么会这样?

这是因为没有 std::ostream::operator<<(char) 重载,所以它会在 std::ostream::operator<<(int) char 被转换为 'a' 和 {{ 之后使用 int 1}} 的 ASCII 值为 97。