函数默认参数和标题

yas*_*sar 48 c++ header

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

extern void apply_surface(int, int, SDL_Surface *, SDL_Surface *,SDL_Rect *);
Run Code Online (Sandbox Code Playgroud)

这是functions.cpp的函数定义

void
apply_surface(int x, int y, SDL_Surface * source, SDL_Surface *
destination,SDL_Rect *clip = NULL)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Luc*_*ore 86

您使声明(即在头文件中 - functions.h)包含可选参数,而不是definition(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*/)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 澄清一下,声明是标题中的一部分. (5认同)

Did*_*set 12

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