c++允许为函数的参数设置默认值,使用起来也很方便,我们常规声明一个函数时如下
int func(int x,int y);
我们可以将第二个参数设置为默认参数,比如设置为1,可以在声明的时候如下
int func(int x, int y = 1);
我们在调用这个函数的时候,如果我们要使用默认的参数,就可以不带第二个参数
func(2);
如果我们对第二个参数赋值了,那就将默认参数覆盖。
我们来看下面一个例子,
#include <iostream>
const int Size = 80;
char *left(const char *str, int n =1);
int main()
{
using namespace std;
char sample[Size];
cout << "Enter a string:\n";
cin.get(sample,Size);
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 *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;
}
left()函数的作用是,返回指定数目的字符串,我们将默认的返回的字符串的数目设定为1.程序执行的结果
要注意的是,对于带参数列表的函数,必须从右向左添加默认值。也就是说,要为某个参数设置默认值,则必须为它右边的所有参数提供默认值
int func1(int n , int m = 4, int j = 5); //VALID
int func2(int n , int m = 4, int j); //INVALID
int func3(int n = 1, int m = 3, int j = 4) //VALID
在调用时,实参从左到右赋值给形参,不能跳过任何参数。
func3(3, , 5);
这种写法是不允许的