入门C++习题

来源:百度知道 编辑:UC知道 时间:2024/06/16 07:19:09
#include <iostream>
using namespace std;
int fun (int a=10,int b=100)
{
return a+b;

}
int main()
{
int x=100;
cout<<fun(x)<<endl;
return 0;
}
这个程序的运行结果是200,为什么呢?

有默认参数傎类型的函数

cout<<fun(x)<<endl;
相当于cout<<f(x,100)<<endl;

同理,如果cout<<f()<<endl;
就相当于cout<<f(10,100)<<endl;

我的答案:
int x=100;
cout<<fun(x)<<endl;
fun(x)中只有一个x,他是前面的int a,因为付值是从左到右的。
那么后面的int b 就是原来的100,而反回的是
return a+b;
所以就是200了。

fun中a,b都是默认参数,如果调用fun的时候给值了就按你传进去的值,如果没有传值,就用默认参数的值。如果调用fun(),返回值就是110.

因为你fun(x)传递过去的给形参是第一个默认参数.形参
a为100。而b也是100。所以a+b=200;