gpt4 book ai didi

c++ - 重载期间提升参数

转载 作者:太空狗 更新时间:2023-10-29 22:57:01 24 4
gpt4 key购买 nike

我正在研究重载,但我对促销完全感到困惑。我查看了 SO ( implicit conversion sequence in function overloading) 中的几篇文章,我确信还有更多文章可用,但找不到合适的文章。我还指的是 http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htm .我在看 Stroustrup 的 C++ Programming 特别版,看到了以下解释。

Finding the right version to call from a set of overloaded functions is done by looking for a best match between the type of the argument expression and the parameters (formal arguments) of the functions. To approximate our notions of what is reasonable, a series of criteria are tried in order: 1 Exact match [2] Match using promotions; [3] Match using standard conversions [4] Match using user-defined conversions [5] Match using the ellipsis ......

void print(int);
void print(double);
void print(long);
void print(char);
void h(char c, int i, short s, float f)
{
print(s); // integral promotion: invoke print(int)
print(f); // float to double promotion: print(double)
}

我写了下面的代码。我在想,如果我调用值为 1 的函数,则 func1(long) 将被调用,因为发生了提升。但我收到错误消息“错误:重载'func1(int)'的调用不明确”。即使是 unsigned char 类型的变量也不会调用函数。

此外,如果我通过调用 func1(3.4f),则会调用 func1(double) 并按照我的预期进行提升。为什么 1 没有提升为 long int 而 float 提升为 double?发生什么整数促销?

    void func1(unsigned char speed)
{
cout<<"Func1 with unsigned char: speed =" << speed <<" RPM\n";
}

void func1(long speed)
{
cout<<"Func1 with long Int: speed =" << speed <<" RPM\n";
}

void func1(double speed)
{
cout<<"Func1 with double: speed =" << speed <<" RPM\n";
}

int main(void)
{
func1(1);
func1(3.4f);
return(0);
}

最佳答案

标准规定:

[C++11: 4.13/1]: ("Integer conversion rank")

Every integer type has an integer conversion rank defined as follows:

  • [..]
  • The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.
  • The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.
  • [..]

在您的示例中需要歧义。

至于func1(3.4f);,只是将float提升为double,这是最匹配的,因为另外两个重载方法有long无符号字符

同时检查这个 table :

enter image description here

子条款规定:

[conv.fpprom]: (7.7 Floating-point promotion )

  • A prvalue of type float can be converted to a prvalue of type double. The value is unchanged.
  • This conversion is called floating-point promotion.

关于c++ - 重载期间提升参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46150905/

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