三元表达式的类型 [英] Type of ternary expression

查看:85
本文介绍了三元表达式的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释以下程序的输出?

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;
}

输出:

第一个字符1

第二个字符49

Output:
First character 1
Second character 49

但是两个 printf 语句应打印相同的字符

But both the printf statements should print the same line.

推荐答案

表达式'1'的类型为 char

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

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

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.)

这篇关于三元表达式的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆