c++:一个被误导的函数重载案例
C++: A misguided case of function overloading
我用c++编写并执行了以下代码:
int calc(int x=10,int y=100);int a,b,s,p,m;void main()
{clrscr();cout<<"enter the two numbers:";cin>>a>>b;s=calc(a,b);p=calc(a);`m=calc();cout<<"n sum:"<<s;cout<<"n product:"<<p;cout<<"n subtraction:"<<m;getch();}
int calc(int a)
{int t;b=100;t=a*b;return t;}
int calc(int a,int b)
{int t;t=a+b;return t;}
int calc()
{int t;t=b-a;return t;}
我看到只有一个函数被调用并且给出了正确的输出。例如:3加4得7,但相乘得101。我不太擅长c++概念。解释一下会很有用。问候。
点
s=calc(a,b);
p=calc(a);
m=calc();
所有匹配函数
int calc(int a, int b)
{
int t;
t=a+b;
return t;
}
因为它已经定义了默认值,如果你没有指定input:
int calc(int x=10, int y=100);
意思是如果你使用
calc(1);
它将使用
calc(1, 100);
BTW,这甚至不能在VisualStudio 2015上编译,因为有错误:
因为您提供了默认值。当您用a=3
调用calc(a)
时,您的程序实际上运行calc(3,100)
第一眼看到代码真是太奇怪了。
首先,你应该知道全局的a = 3, b = 4。这两个参数都是在第一次调用calc时提供的,所以结果是7。第二次,只提供了一个参数,所以a = 3, b = 100而最后一次没有参数,a = 10, b = 100。
int calc(int x = 10, int y = 100)
{
int t;
t = x + y;
return t;
}
这可能更容易理解?
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- C++实用程序,用于将长开关语句转换为封装开关案例阶梯的简洁函数调用
- 如何从函数中返回迭代器,包括结束案例
- 了解构造函数的一些特定案例
- 通过模板构造函数(std ::功能和迷你案例)将构造函数触发
- 也许有人可以看到我缺少什么(调试案例、C++、函数指针)
- 使用案例开关语句加载函数
- 纯虚拟函数调用有趣的案例
- c++:一个被误导的函数重载案例