习题
解答:
1.如果函数非常简单,只有一行的小型非递归函数,适合作为内联函数,因为如果多次调用就会导致调用函数的开销比函数本身运行的开销还大。
但是内联函数只是对函数的一个建议,可以选择听或不听。
a.void song(const char*name, int times = 1);
b.没有,只有原型包含默认值的信息。
c.可以,但要保留times的默认值
include<iostream.h>
void iquote(int n)
{
cout<<" \ " " << n << "\ " " ;
}//用字符"""或字符""打印引号
void iquote(double x)
{
cout<< ' " ' << x << ' " ';
}
void iquote(const char * str)
{
cout << " \ " "<< str << "" " ;
}
a.该函数不修改结构成员,所以使用const限定符
void show(const box &ft)
{
cout<<"Made by "<<ft.maker<<endl;
cout<<"Height = "<<ft.height<<endl;
cout<<"Width = "<<ft.weidth<<endl;
cout<<"Length = "<<ft.length<<endl;
cout<<"volume = "<<ft.volume<<endl;
}
b.要修改成员值
void set_volume(box & ft)
{
ft.volume = ft.heightft.widthft.length;
}
//function to modify array object
void fill(std::array<double,Seasons> & pa);
//function that uses array object without modifying it
void show(std::array<double,Seasons>&da);
fill(expenses);
cin>>pa[i];
两个函数头
a.
double mass(double d,double v = 1.0);//默认参数
double mass(double d,double v);
double mass(double d);//函数重载
b.不能用默认参数
void repeat(int times, const char * str);
void repeat(const char * str);
c.
可以用函数重载
int average(int a,int b);
double average(double a,double b);
d.
特征标相同,无法用函数重载
函数特征标:如果两个函数的参数数目和类型相同,同时参数的排列顺序也相同,则他们的特征标相同,而变量名是不影响的。
template<class T>
T max(T t1,T t2)// or T max(const T &t1, const T &t2)
{
return t1 >t2 ? t1 : t2;
}
8.template<>box max(box b1,box b2)
{
return b1.volume > b2.volume? b1:b2;
}
v1,v2,v3是float型
v4是int型
v5是double型 2.0*m;2.0是double型