问题及代码:
<span style="font-family:SimSun;font-size:14px;color:#333333;">#include <iostream>
using namespace std;
const double pi=3.1415926;
float area(float r=6.5);//指定r的默认值为6.5
float volume(float h,float r=6.5); //指定r的默认值为6.5
int main( )
{
cout<<area()<<endl; //相当于area(6.5);
cout<<area(7.5)<<endl; //形参得到的值为7.5,而不是6.5
cout<<volume(45.6)<<endl; //相当于volume(45.6,6.5)
cout<<volume(34.2,10.4)<<endl; //h的值为34.2,r的值为10.4
return 0;
}
float area(float r)
{
return pi*r*r;
}
float volume(float h,float r)
{
return pi*r*r*h;
}
</span>
运行结果:
1 去掉第 4 行的“=6.5”试试,出错的原因是:第八行在使用area函数时,r没有被定义
2 将第14行改为“float area(float=6.5)”,出错的原因是:
3 将第 5 行“float h,float r=6.5”改为“float h=1,float r”,出错的原因是:
4 将第 5 行改为“float volume(float h=0,float r=6.5)”,带来的改变将是:无
学习心得:
撞错体验,理解函数的默认参数