c++:一个被误导的函数重载案例

C++: A misguided case of function overloading

本文关键字:函数 案例 重载 一个 c++      更新时间:2023-10-16

我用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;
}

这可能更容易理解?