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++ 概念不太了解。解释会很有用。 问候。

因为你给了默认值。当你用 a=3 调用 calc(a) 时,你的程序实际上运行 calc(3,100)

点是

s=calc(a,b); p=calc(a); m=calc(); 全匹配函数

int calc(int a, int b)
  {
  int t;
  t=a+b;
 return t;
  }

因为它已经定义了默认值,如果你不指定输入:

int calc(int x=10, int y=100);

表示如果你使用

calc(1);

它将使用

calc(1, 100);

顺便说一句,这甚至不能在 VisualStudio 2015 上编译,因为有错误:

错误 C2668:'calc':对重载函数的调用不明确

代码乍一看好奇怪

首先,你应该一直知道global 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;
}

这可能更容易理解?