允许使用多个字符的C ++ Char初始化 [英] C++ Char Initialization Allowed With Multiple Characters

查看:91
本文介绍了允许使用多个字符的C ++ Char初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在通过阅读本书学习C ++的过程中,我看到了(对我而言)这奇怪的代码行。

During learning about C++ by reading a book I have seen this (for me) strange line of code.

char ch(‘AB’); //或者char ch ='AB';

这对我来说很奇怪,因为我不知道您可以分配给 char 多个字母而没有任何异常。

It is strange for me because I don't get that you can assign to a char multiple "letters" without getting any exception.

cout << "Characters in ch: " << ch << endl; // Output B

为什么这样做?它在内部如何运作?

Why does this work? And how is it working internally? Is it only saving the last character and ignoring the other ones?

推荐答案

它被称为 多字符文字 ,它们是完全有效的C ++:

It's called a multicharacter literal which are completely valid C++:


多字符文字,例如'AB',具有类型 int 和实现定义的值。

Multicharacter literal, e.g. 'AB', has type int and implementation-defined value.

[...]

许多多字符文字的实现都使用文字中每个char的值以大端顺序对初始化的连续整数字节进行初始化,例如'\1\2\3\4'的值是 0x01020304

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初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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