1 默认参数
函数在声明时可以预先定义默认的形参值。调用时若给出实参则用实参初始化形参,如果没有给出实参则采用预先定义的默认形参值。假设有一个名为left()的函数,它将字符串和n作为参数,并返回该字符串的前n个字符。更准确地说,该函数返回一个指针,该指针指向由原始字符串被选中的部分组成的字符串。例如,函数调用left("thery",3)将创建字符串"the",并返回一个指向该字符串的指针。现在假设第二个参数的默认值为1,则函数调用left("thery",3),3将覆盖默认值。但是调用left("thery")不会出错,它认为第二个参数为1,并返回指向字符串"t"的指针。
left的原型如下:
char * left(const char * str,int n=1);
注意:
(1) 对于带参数列表的函数,必须从右向左添加默认值。也就是说,要为某个参数设置默认值,则必须为它右边的所有参数提供默认值。
(2)实参按从左到右的顺序依次被赋给相应的形参,而不能跳过任何参数。int harpo(int n,int m=4,int j=5);//可以 int harpe(int k=1,int m=2,int n=3);//可以 int harpa(int n,int m=6,int j);//不可以,右边j没赋值
下面来举个默认参数的例子:beeps=harpo(3, ,8);//不行,中间的m没有赋值 beeps=harpo(2);//可以,默认harpo(2,4,5) beeps=harpo(1,8);//可以,默认harpo(1,8,5)
#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; return 0; } char * left(const char * str ,int n) { if(n<0) n=0; char * a=new char[n+1]; int i; for ( i=0;i<n&&strlen(str);i++)//看一下要求的数字和字符串所包含的的那个更长还可以这样写i<n&&str[i],n=(n<strlen(str))?n//:strlen(str) { a[i]=str[i]; } while (i<=n) a[i++]='\0'; return a; }
程序的输出为: