函数参数的默认值 [英] Default value of function parameter
本文介绍了函数参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
1。
int Add (int a, int b = 3);
int Add (int a, int b)
{
}
b $ b
2。
2.
int Add (int a, int b);
int Add (int a, int b = 3)
{
}
$ b b
两者都是工作,这是标准方法和为什么?
推荐答案
如果将声明放在头文件中,并且定义在单独的 .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
lib.cpp
int Add(int a, int b = 3) {
...
}
test.cpp
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);
这篇关于函数参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文