c++入门基础路线
缺省参数
概念:
缺省参数是声明或定义函数时为函数的参数指定一个缺省值。在调用该函数时,如果没有指定实
参则采用该形参的缺省值,否则使用指定的实参。
#include <iostream>
using namespace std;
void Print(int a = 0)
{
cout << a << endl;
}
int main()
{
Print();//没有指定实参,使用参数的默认值(打印0)
Print(10);//指定了实参,使用指定的实参(打印10)
return 0;
}
缺省参数分类
全缺省参数
全缺省参数,即函数的全部形参都设置为缺省参数。
void Func(int a = 10, int b = 20, int c = 30)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
半缺省参数
1、半缺省参数,即函数的参数不全为缺省参数。
void Func(int a, int b = 10, int c = 20)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
注意:
2、半缺省参数必须从右往左依次来给出,不能间隔着给
//错误示例
void Print(int a, int b = 20, int c)
{
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
3、缺省参数不能在函数声明和定义中同时出现
//错误示例
//test.h
void Print(int a, int b, int c = 30);
//test.c
void Print(int a, int b, int c = 30)
{
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
缺省参数只能在函数声明时出现,或者函数定义时出现(二选一则正确)
4、缺省值必须是常量或者全局变量
//正确示例
int x = 30;//全局变量
void Print(int a, int b = 20, int c = x)
{
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
5、C语言不支持(编译器不支持)