加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 重载函数中数据类型的优先级如何?

发布时间:2020-12-16 09:56:42 所属栏目:百科 来源:网络整理
导读:我有3个函数重载.重载函数中数据类型的优先级如何? #include iostreamusing 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); f
我有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?

解决方法

文字有明确定义的类型.特别是,除非加后缀,否则 floating-point literals具有double类型.后缀f或F使其成为float类型的文字,而后缀l或L使其成为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

类似的推理也适用于integer literals – 1是int类型的文字.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读