gpt4 book ai didi

c++ - int8_t 和 uint8_t 是 char 类型吗?

转载 作者:IT老高 更新时间:2023-10-28 13:23:21 25 4
gpt4 key购买 nike

给定这个 C++11 程序,我应该期望看到一个数字还是一个字母?还是不抱期望?

#include <cstdint>
#include <iostream>

int main()
{
int8_t i = 65;
std::cout << i;
}

标准是否指定此类型是否可以或将是字符类型?

最佳答案

来自 C++0x FDIS (N3290) 的 § 18.4.1 [cstdint.syn],int8_t是一个可选的 typedef,指定如下:

namespace std {
typedef signed integer type int8_t; // optional
//...
} // namespace std

§ 3.9.1 [basic.fundamental] 规定:

There are five standard signed integer types: “signed char”, “short int”, “int”, “long int”, and “long long int”. In this list, each type provides at least as much storage as those preceding it in the list. There may also be implementation-defined extended signed integer types. The standard and extended signed integer types are collectively called signed integer types.

...

Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type.

§ 3.9.1 还规定:

In any particular implementation, a plain char object can take on either the same values as a signed char or an unsigned char; which one is implementation-defined.

很容易得出 int8_t 的结论。可能是 char 的 typedef提供char对象采用有符号值;然而,情况并非如此,因为 char不在有符号整数类型(标准和可能扩展的有符号整数类型)列表中。另见 Stephan T. Lavavej's commentsstd::make_unsignedstd::make_signed .

因此,int8_tsigned char 的类型定义或者它是一个扩展的有符号整数类型,其对象恰好占用 8 位存储空间。

不过,要回答您的问题,您不应该做出假设。因为两种形式的功能x.operator<<(y)operator<<(x,y)已定义,§ 13.5.3 [over.binary] 表示我们引用 § 13.3.1.2 [over.match.oper] 来确定 std::cout << i 的解释. § 13.3.1.2 反过来说,实现根据 § 13.3.2 和 § 13.3.3 从候选函数集中进行选择。然后我们查看 § 13.3.3.2 [over.ics.rank] 来确定:

  • template<class traits> basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>&, signed char)如果 int8_t 将调用模板与 signed char 完全匹配(即 signed char 的 typedef)。
  • 否则,int8_t将被提升为 intbasic_ostream<charT,traits>& operator<<(int n)成员函数将被调用。

std::cout << u 的情况下对于 u一个 uint8_t对象:

  • template<class traits> basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>&, unsigned char)如果 uint8_t 将调用模板与 unsigned char 完全匹配.
  • 否则,由于 int可以代表所有uint8_t值,uint8_t将被提升为 intbasic_ostream<charT,traits>& operator<<(int n)成员函数将被调用。

如果你总是想打印一个字符,最安全、最清晰的选择是:

std::cout << static_cast<signed char>(i);

如果你总是想打印一个数字:

std::cout << static_cast<int>(i);

关于c++ - int8_t 和 uint8_t 是 char 类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15911714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com