如何在重载函数时赋予数据类型优先级



我有3个函数过载。重载函数时,数据类型的优先级如何?

#include <iostream>
using namespace std;
void myfunc (int i) {
    cout << "int" << endl;
}
void myfunc (double i) {
    cout << "double" << endl;
}
void myfunc (float i) {
    cout << "float" << endl;
}
int main () {
    myfunc(1);
    float x = 1.0;
    myfunc(x);
    myfunc(1.0);
    myfunc(15.0);
    return 0;
}

输出:

int
float
double
double

程序是如何决定调用float还是double的?

文字具有定义良好的类型。特别是,浮点文字的类型为double,除非有后缀。后缀fF使其成为类型float的文字,而后缀lL使其成为long double的文字。

这解释了观察到的过载分辨率:

myfunc(x);//calls myfunc(float) since x is a float
myfunc(1.0);//calls myfunc(double) since 1.0 is a double
myfunc(15.0);//calls myfunc(double) since 15.0 is a double

类似的推理也适用于整数文字——1int类型的文字。

最新更新