比方说,我们有:C++。为什么std :: cout << char + int打印int值?
char x = 'a';
int y = 1;
所以,如果你运行:
std::cout << x + y;
它打印出98,而不是 'B'。正如我从here看到的 <<operator
只有int参数实现。
从现在开始,我有2个问题:
- 字符+ INT操作后返回什么类型?
- 为什么没有char参数实现,但
std::cout << x
仍然按预期工作并打印char值?
比方说,我们有:C++。为什么std :: cout << char + int打印int值?
char x = 'a';
int y = 1;
所以,如果你运行:
std::cout << x + y;
它打印出98,而不是 'B'。正如我从here看到的 <<operator
只有int参数实现。
从现在开始,我有2个问题:
std::cout << x
仍然按预期工作并打印char值?感谢Fefux,Bo Persson和Matti Virkkunen答案是:
从CPP Reference: Implicit conversions:
算术运算符不接受类型比
int
为 参数小,积分促销是自动在 之后应用左值到右值的转换(如果适用)。
所以返回的x + y
类型是int
。
std::cout
有一个operator<<(char)
作为non-member。
正如你可能知道,C++向后与C.
兼容这两种Ç& C++对待char
就像int
秒。
您可能认为这是该语言的缺陷,但恰恰相反,这非常方便。
假设您要将大写字母转换为相应的小写字母。由于任何大写字母低于相应的小写字母的ASCII码32,这是如此简单:
char c = 'A';
std::cout << (char) (c + 32); // output: 'a'
反之则可以从小写字母转换为大写字母:
char c = 'a';
std::cout << (char) (c - 32); // output: 'A'
“*您可能知道,C++向后兼容C. *”可悲的是,这不是事实。 –
@GillBates,几乎如此。而“几乎”就足够了。 – user7140484
在你的答案的任何地方都找不到“几乎”。 –
阅读:HTTP ://en.cppreference.com/w/cpp/language/implicit_conversion(Section Numeric promotions - > Integral promotion) – Fefux
2)还有一套[非会员运营商<<](http://www.cplusplus。com/reference/ostream/ostream/operator-free /),它也适用于流。 –
而这个:http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2用于为'char'实现'operator <<'。你应该忘记cplusplus.com,这不是一个非常全面的网站。 –