C++到底在什么地方指定默认参数

上节的例子中,我们在函数定义处指定了默认参数。除了函数定义,你也可以在函数声明处指定默认参数。不过当出现函数声明时情况会变得稍微复杂,有时候你可以在声明处和定义处同时指定默认参数,有时候你只能在声明处指定,请看下面的例子(示例1):

#include <iostream>
using namespace std;
void func(int a, int b = 10, int c = 36);
int main(){
    func(99);
    return 0;
}
void func(int a, int b = 10, int c = 36){
    cout<<a<<", "<<b<<", "<<c<<endl;
}

这段代码在编译时会报错,错误信息表明不能在函数定义和函数声明中同时指定默认参数。对代码稍作修改,将 func() 函数的定义放到其他源文件中,如下所示(示例2)。

main.cpp 代码:

#include <iostream>
using namespace std;
void func(int a, int b = 10, int c = 36);
int main(){
    func(99);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_68539124/article/details/129330406