C++中的缺省函数分为全缺省函数和半缺省函数
全缺省函数
void TestFunc(int a=1, int b=2, int c=3) {
cout << a << " " << b << " " << c << endl;
}
这就是一个全缺省函数,在函数的参数列表设置的默认值
如果它被调用
int main() {
TestFunc(100, 200, 300);
TestFunc(100,200);
TestFunc(100);
TestFunc();
system("pause");
return 0;
}
输出的结果是
100,200,300
100,200,3
100,2,3
1,2,3
半缺省函数
void TestFunc(int a, int b=2, int c=1) {
cout << a << " " << b << " " << c << endl;
}
半缺省函数是函数中只给一部分参数默认值
而且要注意的一点是:顺序是从右向左为参数赋值.
如果他被调用
int main() {
TestFunc(100);
return 0;
}
输出
100,2,1
还有一点需要注意
缺省参数不能在函数声明和定义中同时出现