<分区>
在通过阅读一本书学习 C++ 的过程中,我看到了这行(对我来说)奇怪的代码。
char ch('AB');//或者 char ch = 'AB';
这对我来说很奇怪,因为我不明白您可以将多个“字母”分配给 char
而不会出现任何异常。
cout << "Characters in ch: " << ch << endl; // Output B
为什么会这样?它在内部是如何运作的?是否只保存最后一个字符而忽略其他字符?
<分区>
在通过阅读一本书学习 C++ 的过程中,我看到了这行(对我来说)奇怪的代码。
char ch('AB');//或者 char ch = 'AB';
这对我来说很奇怪,因为我不明白您可以将多个“字母”分配给 char
而不会出现任何异常。
cout << "Characters in ch: " << ch << endl; // Output B
为什么会这样?它在内部是如何运作的?是否只保存最后一个字符而忽略其他字符?
最佳答案
它叫做 multicharacter literal这是完全有效的 C++:
Multicharacter literal, e.g.
'AB'
, has typeint
and implementation-defined value.[...]
Many implementations of multicharacter literals use the values of each char in the literal to initialize successive bytes of the resulting integer, in big-endian order, e.g. the value of
'\1\2\3\4'
is0x01020304
.
关于允许多个字符的 C++ Char 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41331212/