C ++.为什么std :: cout<<char + int打印int值? [英] C++. Why std::cout << char + int prints int value?

查看:81
本文介绍了C ++.为什么std :: cout<<char + int打印int值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我们有:

char x = 'a';
int y = 1;

因此,如果您运行:

std::cout << x + y;

它打印98而不是'b'.正如我从此处所看到的<< operator 仅具有 int 参数实现.

It prints 98 instead of 'b'. As i see from here <<operator has only int parameter implementation.

从现在开始,我有2个问题:

From now on i have 2 questions:

  1. char + int 操作后返回什么类型?
  2. 为什么没有 char 参数实现,但 std :: cout<<x 仍能按预期工作并显示 char 值?
  1. After char + int operation what type is returned?
  2. Why there is no char parameter implementation, but std::cout << x still works as expected and prints char value?

推荐答案

感谢 Fefux BoPersson Matti Virkkunen 的答案是:

  1. 来自 CPP参考:隐式转换:

算术运算符不接受小于 int 的类型作为参数,并且积分促销会在之后自动应用左值到右值的转换(如果适用).

arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.

因此, x + y 的返回类型为 int .

So return type of x + y is int.

std :: cout 具有 operator<<(char)作为 查看全文

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