c++中的函数重载不起作用
function overloading in c++ not working
当我运行这个程序时,它会产生错误[Error] call of overloaded 'add(double, double, double)' is ambiguous
。
为什么?我的意思是,函数参数有不同的数据类型,这实际上是函数重载,那么为什么会出错呢?
然而,当浮子被双浮子取代时,它工作得很好。
#include<iostream>
using namespace std;
void add(){
cout<<"I am parameterless and return nothing";
}
int add( int a, int b ){
int z = a+b;
return z;
}
int add(int a, int b, int c){
int z = a+b+c;
return z;
}
int add(float a, float b, float c)
{
int z = a +b + c;
return z;
}
int main()
{
cout<<"The void add() function -> ";
add();
cout<<endl;
cout<<"add(2,3) -> "<<add(2,3)<<endl;
cout<<"add(2,3,4) -> "<<add(2,3,4)<<endl;
cout<<"add(2.1,4.5) -> "<<add(2.8,3.1,4.1)<<endl;
return 0;
}
因为使用double
文本调用函数,而这些函数可以转换为int
或转换为float
,编译器不知道应该选择哪个。
最简单的解决方案是使用float
文字来调用函数:
add(2.8f,3.1f,4.1f)
相关文章:
- 重载运算符 (<<) cout 在 c ++ 中不起作用,当我互相减去两个矩阵时不起作用
- 为什么重载运算符>在参数声明 const 时不起作用?
- 重载"+="运算符:c+=a_times_b 有效,但 c+=a*b 不起作用?
- = 重载不起作用
- 类中的重载函数(Students())是输出输入的信息,但它不起作用
- 重载'='不起作用
- 二叉搜索树<<运算符重载不起作用
- 类构造函数重载不起作用
- c++中的函数重载不起作用
- 两个参数的运算符重载不起作用
- 流运算符重载不起作用
- 代码此外,重载不起作用
- 单例中的构造函数重载不起作用
- c++矩阵重载不起作用
- C++ostream重载不起作用
- 为什么模板运算符重载不起作用?
- 运算符 + 重载不起作用
- c++模板操作符重载不起作用
- sprintf_s模板库重载不起作用
- <<运算符重载不起作用;仍在打印对象地址