Default value of function parameter(函数参数默认值)
问题描述
1.
int Add (int a, int b = 3);
int Add (int a, int b)
{
}
2.
int Add (int a, int b);
int Add (int a, int b = 3)
{
}
两者都有效;这是标准方式,为什么?
Both work; which is the standard way and why?
推荐答案
如果你把声明放在一个头文件中,而定义在一个单独的 .cpp
文件中,并且 #include
来自不同 .cpp
文件的标题,您将能够看到差异.
If you put the declaration in a header file, and the definition in a separate .cpp
file, and #include
the header from a different .cpp
file, you will be able to see the difference.
具体来说,假设:
int Add(int a, int b);
lib.cpp
int Add(int a, int b = 3) {
...
}
test.cpp
#include "lib.h"
int main() {
Add(4);
}
test.cpp
的编译不会看到默认的参数声明,会报错.
The compilation of test.cpp
will not see the default parameter declaration, and will fail with an error.
为此,默认参数定义通常在函数声明中指定:
For this reason, the default parameter definition is usually specified in the function declaration:
int Add(int a, int b = 3);
这篇关于函数参数默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:函数参数默认值


基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01