是否应该在头文件或 .cpp 源文件中指定 C++ 函数默认参数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9260246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Should C++ function default argument values be specified in headers or .cpp source files?
提问by yasar
I am kind of new to C++. I am having trouble setting up my headers. This is from functions.h
我对 C++ 有点陌生。我在设置标题时遇到问题。这是来自functions.h
extern void apply_surface(int, int, SDL_Surface *, SDL_Surface *,SDL_Rect *);
And this is the function definition from functions.cpp
这是来自functions.cpp的函数定义
void
apply_surface(int x, int y, SDL_Surface * source, SDL_Surface *
destination,SDL_Rect *clip = NULL)
{
...
}
And this is how I use it in main.cpp
这就是我在 main.cpp 中使用它的方式
#include "functions.h"
int
main (int argc, char * argv[])
{
apply_surface(bla,bla,bla,bla); // 4 arguments, since last one is optional.
}
But, this doesn't compile, because, main.cpp doesn't know last parameter is optional. How can I make this work?
但是,这不会编译,因为 main.cpp 不知道最后一个参数是可选的。我怎样才能使这项工作?
回答by Luchian Grigore
You make the declaration (i.e. in the header file - functions.h
) contain the optional parameter, not the definition (functions.cpp
).
您使声明(即在头文件中 - functions.h
)包含可选参数,而不是定义 ( functions.cpp
)。
//functions.h
extern void apply_surface(int, int, SDL_Surface *, SDL_Surface *,SDL_Rect * clip = NULL);
//functions.cpp
void apply_surface(int x, int y, SDL_Surface * source, SDL_Surface *
destination,SDL_Rect *clip /*= NULL*/)
{
...
}
回答by Didier Trosset
The default parameter value should be in the function declaration (functions.h), rather than in the function definition (function.cpp).
默认参数值应该在函数声明 (functions.h) 中,而不是在函数定义 (function.cpp) 中。
回答by Michel Keijzers
Use:
用:
extern void apply_surface(int, int, SDL_Surface *, SDL_Surface *,SDL_Rect * = NULL);
(note I can't check it here; don't have a compiler nearby).
(注意我不能在这里检查它;附近没有编译器)。