在创建默认变元的函数时,只能指定一次默认值,而且必须在文件中第一次声明函数时。也可以在函数的定义中。
所有带默认参数的变元必须出现在不带默认参数变元的右边。
默认参数的变元可以出现在类的构造函数中。
测试代码:
#include<iostream>
using namespace std;
void show(int x=10)
{
cout<<"x is "<<x<<endl;
}
int main()
{
int max(int x=10,int y=10);
show();
show(100);
cout<<max()<<endl;
cout<<max(1,3)<<endl;
cout<<max(3,1)<<endl;
cout<<max(3,3)<<endl;
return 0;
}
int max(int x,int y)
{
if((x-y)>0)
return x;
else
{
if(x==y)
return 0;
else
return y;
}
}
测试结果:
x is 10
x is 100
0
3
3
0
Press any key to continue
默认变元与函数重载的关系
测试代码:
#include<iostream>
#include<cstring>
using namespace std;
void mystrcat(char *s1,const char *s2,int len)
{
if(len==-1)
strcat(s1,s2);
else
strncat(s1,s2,len);
}
void mystrcat(char *s1,const char *s3,int len=-1);
int main()
{
char str1[80]="hello ";
char str2[]="world";
mystrcat(str1,str2);
cout<<str1<<endl;
mystrcat(str1,str2,3);
cout<<str1<<endl;
return 0;
}
测试结果:
hello world
hello worldwor
Press any key to continu