三元表达的类型

ami*_*per 31 c++ cout ternary-operator

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

#include <iostream>
using namespace std;

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

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

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

但这两个printf陈述应该打印相同的行.

Ker*_* SB 34

表达式的类型'1'char.

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

因此,<<操作符的两个调用选择不同的重载:前者按原样打印字符,后者将整数格式化为十进制字符串表示.(字符的整数值'1'由基本字符集定义.)


mar*_*inj 5

cout(test ? 3 : '1')在推导出适当的后,将显示表达式的值<<operator.在这种情况下int,您可以使用Scott Meyers在其最新书中传播的精彩技巧来检查它:

template < typename T > class TD; // Type Displayer
int main()
{
  int test = 0;
  TD<decltype((test ? 3 : '1'))> xType; 

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这会生成错误,这也会为您提供表达式类型的信息:

main.cpp:6:34:错误:聚合'TD < int > xType'的类型不完整,无法定义TD xType;

是的int.现在static_cast<int>('1')是49岁.

  • `static_cast <int>('1')`在许多系统上都是49,但它不是必需的.有些系统并非如此. (2认同)