Type of ternary expression

泄露秘密 提交于 2020-01-03 06:44:06

问题


Can anyone explain the output of the following program:

#include <iostream>
using namespace std;

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

   return 0;
}

Output:
First character 1
Second character 49

But both the printf statements should print the same line.


回答1:


The type of the expression '1' is char.

The type of the expression (test ? 3 : '1') is at least int (or an unsigned version thereof; portably it is std::common_type_t<int, char>).

Therefore the two invocations of the << operator select different overloads: The former prints the character as is, the latter formats the integer as its decimal string representation. (The integral value of the character '1' is defined by your base character set.)




回答2:


cout will display value of (test ? 3 : '1') expression after deducing appropriate <<operator. In this case it is int, you can check it using nice trick that Scott Meyers propagated in his newest book:

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

  return 0;
}

this generates error, which will also give you information of type of your expression:

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

which is int. And static_cast<int>('1') is 49.



来源:https://stackoverflow.com/questions/30018841/type-of-ternary-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!