c++之函数的其它用法

在c++中,可以给函数的形参赋予默认值。

#include<iostream>
using namespace std;

//如果某个位置有了默认值,那么之后的形参也必须有默认值
//如果函数声明有默认参数,函数实现就不能有默认参数
//若果传入的参数覆盖了形参的默认值,就使用新的值,否则还是使用默认值;
int add(int a, int b = 1, int c = 2) {
    return a + b + c;
}

int main() {
    int res1 = add(1);
    cout << res1 << endl;
    int res2 = add(1,10,12);
    cout << res2 << endl;
    system("pause");
    return 0;

}

函数占位参数:调用时必须被填补。

#include<iostream>
using namespace std;

//占位参数还可以有默认值
void add(int a, int = 30) { cout<<"调用函数"<<endl; } int main() { add(10,20); system("pause"); return 0; }
原文地址:https://www.cnblogs.com/xiximayou/p/12084864.html