c++ - 在 C++ 中重载函数

标签 c++

<分区>

我正在通过 Sololearn 学习 C++。我对函数重载有疑问

这是代码

#include<iostream>
using namespace std;


void printSomething(int x)   {

   cout << "I'm printing an integer " << x << endl;
}
void printSomething(float x)   {

   cout << "I'm printing a float " << x << endl;
}

int main()  {

   int a =3; 
   float b = 2.65;
   printSomething(a);
   printSomething(b);
   return 0;
}

输出为

               I'm printing an integer 3 
               I'm printing a float 2.65

但是如果我在调用函数时直接给出参数

像这样

#include<iostream>
using namespace std;


void printSomething(int x)   {

   cout << "I'm printing an integer " << x << endl;
}
void printSomething(float x)   {

   cout << "I'm printing a float " << x << endl;
}

int main()  {

   printSomething(3);
   printSomething(2.65);
   return 0;
}

出现以下错误

..\Playground: In function 'int main()': ..\Playground:19:24: error: call of overloaded 'printSomething(double)' is ambiguous printSomething(2.65); ^ ..\Playground:19:24: note: candidates are: ..\Playground:5:6: note: void printSomething(int) void printSomething(int x) { ^ ..\Playground:9:6: note: void printSomething(float) void printSomething(float x) { ^

但如果我改变

void printSomething(float x)   {

    cout << "I'm printing a float " << x << endl;
}

void printSomething(double x)   {

    cout << "I'm printing a float " << x << endl;
}

我将得到输出

       I'm printing a float 2.65

这是为什么呢? 但如果它只是整数,它就可以正常工作

#include<iostream>
using namespace std;


void printSomething(int x)   {

   cout << "I'm printing an integer " << x << endl;
}
void printSomething(float x)   {

   cout << "I'm printing a float " << x << endl;
}

int main()  {

    printSomething(3);
    return 0;
}

结果

                      I'm printing an integer 3

为什么这不适用于 float

谢谢

最佳答案

2.65 不是 float 文字,它是 double 文字。

因此编译器不知道您是想将double 转换为float 还是int,因此会发出错误。

在第一种情况下,当编写 float b = 2.65; 时,编译器假设您知道自己在做什么,并且使用 b 调用重载是明确的。

如果您编写了 printSomething(2.65f); 那么这也将是明确的:2.65f 是一个 float 文字。

关于c++ - 在 C++ 中重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38243148/

相关文章:

c++ - 如何使用 glUniformMatrix4fv 将 4x4 变换矩阵传递和使用到 vShader 中?

c++ - std::chrono time_since_epoch 的默认持续时间

c++ - C++ 抽象语法树组合和代码生成库

C++Concurrency in action :Can the Listing7. 6(使用危险指针的 pop() 实现)真的检测到无法回收的节点吗?

C++ - 通过 ref 传递数组

c++ - 为什么有人会使用 C 而不是 C++?

c++ - 如何在 C++ 中将字符串转换为模板化类型

c++ - 获取用于 for 循环的数组大小

c++ - 使用 makefile 编译 C++ 11 程序的简单方法

c++ - Loadlibrary excatly #import 做什么?