三元表达式的类型

Type of ternary expression

任何人都可以解释以下程序的输出:

#include <iostream>
using namespace std;

int main()
{
   int test = 0;
   cout << "First  character " << '1' << endl;
   cout << "Second character " << (test ? 3 : '1') << endl;

   return 0;
}

输出:
第一个字符 1
第二个字符 49

但是 printf 两个语句应该打印同一行。

表达式'1'的类型是char

表达式(test ? 3 : '1')的类型至少是int(或其无符号版本;可移植的是std::common_type_t<int, char>)。

因此 << 运算符的两次调用 select 不同的重载:前者按原样打印字符,后者将整数格式化为其十进制字符串表示形式。 (字符的整数值 '1' 由您的基本字符集定义。)

cout 将在推导适当的 <<operator 后显示 (test ? 3 : '1') 表达式的值。在这种情况下,它是 int,您可以使用 Scott Meyers 在他的 newest book:

中传播的巧妙技巧来检查它
template < typename T > class TD; // Type Displayer
int main()
{
  int test = 0;
  TD<decltype((test ? 3 : '1'))> xType; 

  return 0;
}

这会产生错误,它还会为您提供表达式类型的信息:

main.cpp:6:34: error: aggregate 'TD<int> xType' has incomplete type and cannot be defined TD xType;

intstatic_cast<int>('1') 是 49.