gpt4 book ai didi

c++ - C++中的整数提升和整数转换有什么区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:02:59 26 4
gpt4 key购买 nike

C++ 标准的第 4.5 节(整数提升)讨论了将整数类型转换为具有更高级别的类型的具体情况。

C++ 标准的第 4.7 节(整数转换)以(项目符号 4.7.1)开头:

An rvalue of an integer type can be converted to an rvalue of another integer type. An rvalue of an enumeration type can be converted to an rvalue of an integer type.

据我了解,4.5 中描述的转换(可能除了项目符号 4.5.3(枚举))可以单独使用 4.7 部分中的技术来执行:4.5.1 和 4.5.2 完全包含在 4.7 中。 1; 4.5.4 包含在 4.7.4 中。那么整个 4.5 节的目的是什么?它启用了哪些额外的转换?也许我缺少一些限制?

附言我正在阅读标准的 C++03 版本。

最佳答案

认为区别很重要,因为两者不属于相同的转换类别并且具有不同的排名(参见 13.3.3.1 .1,标准转换序列)。在重载决议方面,排名有所不同:

Standard conversion sequences are ordered by their ranks: an Exact Match is a better conversion than a Promotion, which is a better conversion than a Conversion.

最后,我认为是 4.5 和 4.7 之间的区别使得以下代码没有歧义:

#include <iostream>

void foo(int i) { std::cout << "foo(int)" << std::endl; }
void foo(unsigned short i) { std::cout << "foo(unsigned short)" << std::endl; }

int main()
{
foo(static_cast<short>(1));
}
  • shortint 是一个提升(因此有提升等级)
  • shortunsigned short 是一次转换(因此有转换等级)

最后,这段代码调用了 foo(int),因为它是一个更好的候选者。

关于c++ - C++中的整数提升和整数转换有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4640543/

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