函数默认参数和标题

时间:2012-02-13 12:07:24

标签: c++ header

我是C ++的新手。我在设置标题时遇到问题。这是 来自functions.h

extern void apply_surface(int, int, SDL_Surface *, SDL_Surface *,SDL_Rect *);

这是functions.cpp

中的函数定义
void
apply_surface(int x, int y, SDL_Surface * source, SDL_Surface *
destination,SDL_Rect *clip = NULL)
{
    ...
}

这就是我在main.cpp中使用它的方式

#include "functions.h"
int
main (int argc, char * argv[])
{
    apply_surface(bla,bla,bla,bla); // 4 arguments, since last one is optional.
}

但是,这不会编译,因为,main.cpp不知道last参数是可选的。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:76)

您声明(即在头文件中 - 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*/)
{
    ...
}

答案 1 :(得分:9)

默认参数值应该在函数声明(functions.h)中,而不是在函数定义(function.cpp)中。

答案 2 :(得分:2)

使用:

extern void apply_surface(int, int, SDL_Surface *, SDL_Surface *,SDL_Rect * = NULL);

(注意我不能在这里检查;附近没有编译器。)

相关问题