C++_08_函数默认参数和占位参数
默认参数
函数定义时,定义默认参数,当后面调用时传入新的参数,则覆盖默认参数,使用新参数;否则使用默认参数
注意:如果调用函数时不传入新的参数,那么定义函数时一定要传入默认参数
#include <iostream> using namespace std; void myPrint(int x = 3) //默认值 x = 3 { cout<<"x = "<<x<<endl; } //1 若 你填写参数,使用你填写的,不填写默认 //2 在默认参数规则 ,如果默认参数出现,那么右边的都必须有默认参数 void myPrint2( int m, int n, int x = 3, int y = 4) //void myPrint2( int m, int n, int x = 3, int y ) { cout<<"x"<<x<<endl; } int main() { myPrint(4); myPrint(); //这里没传值,那么函数定义一定要给一个默认值 // cout<<"hello..."<<endl; system("pause"); return 0; }
zl@LAPTOP-2ABL2N6V:/mnt/d/VsCode$ g++ 07-函数参数.cpp -o 07-函数参数 zl@LAPTOP-2ABL2N6V:/mnt/d/VsCode$ ./07-函数参数 x = 4 x = 3 hello... sh: 1: pause: not found zl@LAPTOP-2ABL2N6V:/mnt/d/VsCode$
占位参数
占位参数就是在函数定义的时候要预定“位置”,调用函数的时候传参将预定的座位坐满
#include <iostream> using namespace std; //函数占位参数 函数调用是,必须写够参数 void func1(int a, int b, int) { cout << "a = " << a << " b = " << b << endl; } int main() { //func1(1, 2); //err调用不起来 func1(1, 2, 3); //定义函数时设置了几个参数,传入新参是必须参入刚好相同数量个参数 //一个不能少,也一个不能多return 0; }
默认参数和占位参数可以同时存在
1、默认参数就是在函数定义的时候定义一个默认值,属于保险起见有个底牌;
2、占位参数就是在函数定义的时候要求定义出参数个数的位置,就是要提前预定好位置,当传参的时候一定要将预定的位置都占满
3、但是当定义函数时提前定义好默认参数后,即使调用函数传参时占位参数没传满也没关系,因为有默认参数候补着呢!无论如何预定的位置都会被占满的(先做足充分准备,后即使有漏洞也不会出大问题)
#include <iostream> using namespace std; //默认参数和占位参数 void func2(int a, int b, int c=0) {
cout << "a = " << a << " b = " << b << " c = " << c << endl;
}
int main() { func2(1, 2); //0k func2(1, 2, 3); //okreturn 0; }
zl@LAPTOP-67MRI3LV:/mnt/d/VsCode$ ./a.out a=1;b=2;c=0 a=1;b=2;c=3

浙公网安备 33010602011771号