[C++基础]006_函数默认参数
1 int function(int a, int b = 0) 2 { 3 cout<<"a + b = "<<(a+b)<<endl; 4 return 0 ; 5 }
上面的 int b = 0就是默认参数了,如果不传入b值的话,函数默认将使用b=0.
注意:
默认参数必须出现在结尾,或连续结尾。即如下的声明是非法的:
1 int function(int a=0, int b) 2 { 3 cout<<"a + b = "<<(a+b)<<endl; 4 a = 10; 5 b = 20; 6 return 0 ; 7 }
而下面是合法的:
1 int function(int a, int b=2, int c=1) 2 { 3 cout<<"a + b = "<<(a+b)<<endl; 4 a = 10; 5 b = 20; 6 return 0 ; 7 }
下面的也是合法的:
1 int function(int a=1, int b=2) 2 { 3 cout<<"a + b = "<<(a+b)<<endl; 4 a = 10; 5 b = 20; 6 return 0 ; 7 }