允许多个字符的 C++ Char 初始化

标签 c++ char

<分区>

在通过阅读一本书学习 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 type int 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' is 0x01020304.

关于允许多个字符的 C++ Char 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41331212/

相关文章:

c++ - 将 vector 声明为类成员

c++ - 在 C++ 中,函数 void foo(int** p) 有什么用?

css - 哪个英文字母占据了最多的像素?

c++ - 动态分配内存给字符指针

c++ - 初始化字符矩阵时出现 EAccess 冲突

C++ Ifstream 读太多?

将 char 复制到 char 数组

c++ - 运算符重载 = 和模板 double 值仅对 int 不起作用

c++ - 编写一个 ostream 过滤器?

c++ - 带有 openframeworks/opengl 的色度键