C++,函数重载问题

发布于 2024-10-09 06:44:41 字数 996 浏览 0 评论 0原文

我在这个例子中遇到了麻烦。每当我发送任何参数时,它都会给出编译器错误:

prog.cpp: In function ‘int main()’:
prog.cpp:11: error: call of overloaded ‘add(std::basic_istream<char, std::char_traits<char> >&, std::basic_istream<char, std::char_traits<char> >&)’ is ambiguous
prog.cpp:4: note: candidates are: int add(int, int) <near match>
prog.cpp:6: note:                 char add(char, char) <near match>

我个人认为当我将参数作为 int 或 char 发送时应该发生此错误,但是当我发送 float 参数时,错误仍然存​​在。请帮忙。谢谢

/*Function Overloading*/
#include<iostream>
using namespace std;
int add(int a,int b);
float add(float a,float b);
char add(char a,char b);
int main()
{
float a,b;
  cout<<"Enter Two numbers to add them"<<'\n';
  add(cin>>a,cin>>b);
  return 0;
}
int add(int a,int b)
{
//cin>>a,b;
return a+b;
}
float add(float a,float b)
{
//cin>>a,b;
return a+b;
}
char add(char a,char b)
{
//cin>>a,b;
return a+b;
}

I am having a trouble in this example.Whenever I send any arguments,it gives compiler error:

prog.cpp: In function ‘int main()’:
prog.cpp:11: error: call of overloaded ‘add(std::basic_istream<char, std::char_traits<char> >&, std::basic_istream<char, std::char_traits<char> >&)’ is ambiguous
prog.cpp:4: note: candidates are: int add(int, int) <near match>
prog.cpp:6: note:                 char add(char, char) <near match>

I personally think that this error should occur when I am sending the arguments as int's or char's but when I send float arguments,the error still remains.Please help.Thanks

/*Function Overloading*/
#include<iostream>
using namespace std;
int add(int a,int b);
float add(float a,float b);
char add(char a,char b);
int main()
{
float a,b;
  cout<<"Enter Two numbers to add them"<<'\n';
  add(cin>>a,cin>>b);
  return 0;
}
int add(int a,int b)
{
//cin>>a,b;
return a+b;
}
float add(float a,float b)
{
//cin>>a,b;
return a+b;
}
char add(char a,char b)
{
//cin>>a,b;
return a+b;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小…楫夜泊 2024-10-16 06:44:41

cin>> x 返回 cin,而不是 x。 还可以尝试

cin >> a >> b;
add(a, b);

cin >> 这样的语法a,b 无效,使用>>多次。

cin >> x returns cin, not x. Try

cin >> a >> b;
add(a, b);

Also syntax like cin >> a, b is invalid, use >> multiple times.

习惯成性 2024-10-16 06:44:41

而不是

add(cin>>a,cin>>b);

write

cin>>a;cin>>b;
add(a,b);

流读取操作返回流,而不是读取的值。

Instead of

add(cin>>a,cin>>b);

write

cin>>a;cin>>b;
add(a,b);

The stream read operation returns the stream, not the value read.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文