gpt4 book ai didi

c++ - 将枚举传递给整数类型的参数

转载 作者:行者123 更新时间:2023-12-05 02:30:27 25 4
gpt4 key购买 nike

考虑以下代码:

enum ABC : char
{
a, b, c
};

void ff(char c)
{
cout << "char\n";
}

void ff(int i)
{
cout << "int\n";
}

int main()
{
ff(a); // char
}

请问为什么编译器匹配ff(char)而不是ff(int)


我在阅读C++ Primer(第 5 版)时想到了这个问题。在第 835 页,作者声明:

... we can pass an object or enumerator of an unscoped enumeration to a parameter of integral type. When we do so, the enum value promotes to int or to a larger integral type ... Regardless of its underlying type, objects and the enumerators ... are promoted to int.

我对上述引述的理解是,当传递给需要整型参数的函数时,枚举数将首先“至少”转换为 int。所以,我期待上面的代码调用 ff(int)。实际上,即使是我的 Visual Studio 编辑器也显示:(抱歉,我知道我们应该避免在此处使用屏幕截图,但我只想展示我所看到的)

我还注意到,如果我没有明确指定 ABC 的底层类型,那么 ff(int) 将被调用。

所以我目前的猜测是这样的:如果我们没有明确指定底层类型,那么传递给整数参数的对象/枚举器将首先被转换为 int。但如果显式指定了底层类型,那么编译器将首先尝试匹配需要指定类型的重载函数。

请问我的猜测是否正确?

最佳答案

May I ask why complier matches ff(char) instead of ff(int)?

因为具有固定底层类型的枚举可以隐式转换为其底层类型。底层类型是 char,因此转换为 char 是首选的候选重载。

So my current guess goes like this: If we don't explicitly specify the underlying type, then the object/enumerator passed to the integral parameter will first be casted into an int.

强制转换是一种显式转换。此示例中的转换是隐式的。

确切的首选转换取决于枚举的值。语言规则有点复杂,所以我从标准中逐字复制:

[conv.prom]

A prvalue of an unscoped enumeration type whose underlying type is not fixed can be converted to a prvalue of the first of the following types that can represent all the values of the enumeration ([dcl.enum]): int, unsigned int, long int, unsigned long int, long long int, or unsigned long long int.If none of the types in that list can represent all the values of the enumeration, a prvalue of an unscoped enumeration type can be converted to a prvalue of the extended integer type with lowest integer conversion rank ([conv.rank]) greater than the rank of long long in which all the values of the enumeration can be represented.If there are two such extended types, the signed one is chosen.

May I ask if my guess is correct?

在这种情况下,int 是一个正确的猜测,因为它是引用标准规则列表中的第一个类型,它可以表示枚举的所有值,即 0、1 2。但猜测并不普遍适用。

关于c++ - 将枚举传递给整数类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71842332/

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