gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:10:18 25 4
gpt4 key购买 nike

<分区>

我正在通过 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

谢谢

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com