简体   繁体   English

C ++中函数重载的困惑

[英]Confusion in function overloading in c++

My program has two print functions: one for int and one for float . 我的程序有两个打印功能:一个用于int ,一个用于float

void print(float a){
    cout << "float:" << a << endl;
}

void print(int a){
    cout << "integer:" << a << endl;
}

Whenever I call print(10) or print(0) the one for int datatype is called. 每当我调用print(10)print(0) ,都会调用int数据类型。 But when I try to call print(3.5) , it gives compilation error. 但是,当我尝试调用print(3.5) ,会出现编译错误。 Why is it so? 为什么会这样呢?

PS when I have only one print function void print(float a) then print(3.5) works fine. PS,当我只有一个print功能时, void print(float a)那么print(3.5)可以正常工作。

Note that 3.5 is a double , not a float . 注意3.5是一个double float ,而不是float And it could be converted to both float and int implicitly, the invoking becomes ambiguous ( float with int ). 而且它可以隐式转换为floatint ,调用变得不明确( float with int )。

See floating point literal . 请参见浮点文字

suffix, if present, is one of f , F , l , or L . 后缀(如果存在)是fFlL The suffix determines the type of the floating-point literal: 后缀确定浮点文字的类型:

  (no suffix) defines double f F defines float l L defines long double 

So you can call it by print(3.5f); 因此,您可以通过print(3.5f);来调用它print(3.5f); to avoid ambiguity. 避免歧义。

BTW: double could be converted to float implicitly, that's why if you have only one function then it works well. 顺便说一句: double可以隐式转换为float ,这就是为什么如果您只有一个函数,那么它会很好地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM