char、wchar_t、char16_t、char32_tchar, wchar_t, char16_t, char32_t

类型charwchar_tchar16_tchar32_t是表示字母数字字符的内置类型,以及非字母数字的标志符号和非打印字符。The types char, wchar_t, char16_t and char32_t are built-in types that represent alphanumeric characters as well as non-alphanumeric glyphs and non-printing characters.

语法Syntax

char     ch1{ 'a' };  // or { u8'a' }
wchar_t  ch2{ L'a' };
char16_t ch3{ u'a' };
char32_t ch4{ U'a' };

备注Remarks

Char类型是 C 和 C++ 中的原始字符类型。The char type was the original character type in C and C++. 类型无符号 char通常用于表示字节,这不是 C++ 中的内置类型。The type unsigned char is often used to represent a byte, which is not a built-in type in C++. Char类型可以用于存储中的字符的 ASCII 字符集或任何 ISO-8859 字符集,并且各个字节多字节字符,如 Shift JIS 或 Unicode 字符集的 utf-8 编码。The char type can be used to store characters from the ASCII character set or any of the ISO-8859 character sets, and individual bytes of multi-byte characters such as Shift-JIS or the UTF-8 encoding of the Unicode character set. 字符串char类型被称为缩小字符串,即使使用多字节字符进行编码。Strings of char type are referred to as narrow strings, even when used to encode multi-byte characters. 在 Microsoft 编译器char是一个 8 位类型。In the Microsoft compiler, char is an 8-bit type.

Wchar_t类型是实现定义的宽字符类型。The wchar_t type is an implementation-defined wide character type. 在 Microsoft 编译器,它表示用来存储 Unicode 编码为 UTF 16LE 的 16 位宽字符在 Windows 操作系统上的本机字符类型。In the Microsoft compiler, it represents a 16-bit wide character used to store Unicode encoded as UTF-16LE, the native character type on Windows operating systems. 宽字符版本的通用 C 运行时 (UCRT) 库函数使用wchar_t和其指针和数组类型作为参数和返回值是否为本机 Windows API 的宽字符版本。The wide character versions of the Universal C Runtime (UCRT) library functions use wchar_t and its pointer and array types as parameters and return values, as do the wide character versions of the native Windows API.

Char16_tchar32_t类型分别表示 16 位和 32 位的宽字符。The char16_t and char32_t types represent 16-bit and 32-bit wide characters, respectively. Unicode 编码为 utf-16 可以存储在char16_t类型和 Unicode 编码为 UTF-32 可以存储在char32_t类型。Unicode encoded as UTF-16 can be stored in the char16_t type, and Unicode encoded as UTF-32 can be stored in the char32_t type. 这些类型的字符串和wchar_t是所有被称为字符串,但此术语通常专指的字符串wchar_t类型。Strings of these types and wchar_t are all referred to as wide strings, though the term often refers specifically to strings of wchar_t type.

在 C++ 标准库,basic_string类型专用于窄和宽字符串。In the C++ standard library, the basic_string type is specialized for both narrow and wide strings. 使用std::string字符时的类型都是charstd::u16string字符时的类型都是char16_tstd::u32string字符时的类型都是char32_t,并std::wstring字符时的类型都是wchar_tUse std::string when the characters are of type char, std::u16string when the characters are of type char16_t, std::u32string when the characters are of type char32_t, and std::wstring when the characters are of type wchar_t. 表示文本,其他类型包括std::stringstreamstd::cout均可专用于窄和宽字符串。Other types that represent text, including std::stringstream and std::cout have specializations for narrow and wide strings.