代码之家  ›  专栏  ›  技术社区  ›  Rajesh

过载期间参数的提升

  •  4
  • Rajesh  · 技术社区  · 7 年前

    我当时正在研究超载问题,我完全被促销搞糊涂了。我看了一些文章,所以( implicit conversion sequence in function overloading http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htm . 我在看Stroustrup的C++编程特别版时,看到了下面的解释。

    从一组重载函数中查找要调用的正确版本 通过在参数类型之间寻找最佳匹配来完成 函数的表达式和参数(形式参数)。到 1 精确匹配[2]使用促销的匹配; [3] 使用标准转换进行匹配[4]使用用户定义的 转换[5]使用省略号匹配。。。。。。

    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)
    }
    

    此外,如果我传递调用func1(3.4f),则调用func1(double),并根据我的期望进行升级。为什么1没有提升为长int,但为什么浮点提升为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);
        }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Community CDub    5 年前

    本标准规定:

    [C++11: 4.13/1]: (“整数转换秩”)

    • 排名 long long int 排名 long int 哪一个 应大于 int short int ,其应大于签名字符的秩。
    • 任何无符号整数类型的秩应等于相应有符号整数类型的秩。

    这就需要在你的例子中产生歧义。

    至于 func1(3.4f); ,它只是从float提升到double,这是最好的匹配,因为其他两个重载方法 long unsigned char .

    table

    enter image description here

    其中子条款规定:

    [conv.fpprom]: (7.7浮点提升)

    • float 可以转换为类型为的prvalue double . 该值不变。