默认参数
默认参数——当函数调用中省略了实参时自动使用的值。
通过函数原型设置默认值,将值赋给原型中的参数:
char * left(const char * str, int n = 1);
对于带参数列表的函数,必须从右向左添加默认值。也就是说,要为某个参数设置默认值,则必须为它右边的所有参数提供默认值:
int harpo(int n, int m = 4, int j = 5); //有效
int chico(int n, int m = 6, int j); //无效
int groucho(int k = 1, int m = 2, int n = 3); //有效
则harpo()原型允许调用该函数时提供1个、2个或3个参数:
beeps = harpo(2); //相当于harpo(2,4,5)
beeps = harpo(1,8); //相当于harpo(1,8,5)
beeps = harpo(8,7,6); //没有用到默认参数
实参按从左到右的顺序依次被赋给相应的形参,而不能跳过任何参数。因此,下面的调用是不允许的:
beeps = harpo(3,,8); //无效
程序8.9
#include <iostream>
const int ArSize = 80;
char * left(const char * str, int n = 1);
int main()
{
using namespace std;
char sample[ArSize];
cout << "Enter a string:\n";
cin.get(sample, ArSize);
char *ps = left(sample, 4);
cout << ps << endl;
delete [] ps;
ps = left(sample);
cout << ps << endl;
delete [] ps;
system("pause");
return 0;
}
char * left(const char * str, int n)
{
if (n < 0)
n = 0;
char * p = new char[n + 1];
int i;
for (i = 0; i < n&&str[i]; i++)
p[i] = str[i];
while (i <= n)
p[i++] = '\0';
return p;
}