C + + 函数的默认参数值是否应该在头文件或.cpp 源文件中指定?

我对 C + + 还是个新手。我在设置头文件时遇到了麻烦。这是 来自 function. 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 不知道最后一个参数是可选的?

65165 次浏览

You make the declaration (i.e. in the header file - functions.h) contain the optional parameter, not the 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*/)
{
...
}

The default parameter value should be in the function declaration (functions.h), rather than in the function definition (function.cpp).

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).

Strangely enough, it works fine for me if I have a virtual function without a default parameter, and then inheritors in .h files without default parameters, and then in their .cpp files I have the default parameters. Like this:

// in .h
class Base {virtual void func(int param){}};
class Inheritor : public Base {void func(int param);};
// in .cpp
void Inheritor::func(int param = 0){}

Pardon the shoddy formatting