【发布时间】:2016-07-07 18:39:41
【问题描述】:
我正在通过 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:在函数“int main()”中: ..\Playground:19:24: 错误: 重载 'printSomething(double)' 的调用不明确 printSomething(2.65); ^ ..\Playground:19:24: 注意:候选人是: ..\Playground:5:6: 注意:无效 printSomething(int) 无效 printSomething(int x) { ^ ..\Playground:9:6: 注意: void printSomething(float) 无效 printSomething(浮动 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
为什么这不适用于浮动
谢谢
【问题讨论】:
-
因为
2.65是double文字,而不是float。你可以试试printSomething(2.65f);; -
@songyuanyo 那么当我将它声明为浮点数时它是如何工作的,如第一个程序所示 int main() { int a =3;浮动 b = 2.65; printSomething(a); printSomething(b);返回0;在这里我声明 2.65 为 float 而不是 double?
-
因为
b是float(正如您声明的那样)。 -
所以如果直接给函数'printSomething(2.65)'会变成双倍吗?
-
这是因为隐式类型转换。为了避免这种情况,请给出类似 printSomething((float)2.65);
标签: c++