C++ 为函数Y的参数X给定的默认参数

C++ 为函数Y的参数X给定的默认参数,c++,parameters,C++,Parameters,我正在尝试为此函数声明中的参数指定默认值: bool gatt_db_service_set_active(struct gatt_db_attribute *attrib, bool active, int fd=0); 然而,我得到了一个错误 “bool gatt\u db\u service\u set\u active(gatt\u db\u attribute*,bool,int)”参数3的默认参数[-fppermissive] 然后它说: “bool gatt\u db\u ser

我正在尝试为此函数声明中的参数指定默认值:

bool gatt_db_service_set_active(struct gatt_db_attribute *attrib, bool active, int fd=0);
然而,我得到了一个错误

“bool gatt\u db\u service\u set\u active(gatt\u db\u attribute*,bool,int)”参数3的默认参数[-fppermissive]

然后它说:

“bool gatt\u db\u service\u set\u active(gatt\u db\u attribute*,bool,int)”中的先前规范如下:
bool gatt_db_service_set_active(struct gatt_db_attribute*attrib,bool active,int fd;结果是在我声明函数的头中没有头保护

我发现错误指向自身很奇怪,所以我尝试通过简单地添加一个标题保护来解决它,如顶部的
\ifndef FOO
\define FOO
,底部的
\endif
。这很有效


如果您以某种方式声明了函数两次(因此编译器会看到两行类似的内容),那么感谢您的指针!

然后你会看到这个错误,因为有两个默认的声明,这是C++标准不允许的(第83.6节,第4节):

这说明了错误。请注意,如果不重新定义默认值,则可以对函数进行乘法声明,这对于正向声明可能很有用

这可能是因为缺少包含保护,在这种情况下,编译器会告诉您两个声明位于同一行。在以下情况下可能会出现这种情况:

// header.h
// No include guard!
bool gatt_db_service_set_active(struct gatt_db_attribute *attrib, bool active, int fd=0);
// ^^ compiler error on this line

// otherheader.h
#include "header.h"

// impl.cpp
#include "header.h"
#include "otherheader.h"

void main()
{} 
解决方案是一个包含保护,如下所示:

bool gatt_db_service_set_active(struct gatt_db_attribute *attrib, bool active, int fd=0);
// header.h
#ifndef HEADER__H_
#define HEADER__H_

bool gatt_db_service_set_active(struct gatt_db_attribute *attrib, bool active, int fd=0);

#endif // HEADER__H_

这将防止第二次(以及随后的)<代码>页码。h < /C> >声明同一件事情两次。

你确定你的文件是否有CPP不是C扩展?我确信,这都是C++。虽然这个错误发生在从C到C++的移植。奇怪的是,不同的头文件的其他函数用默认参数工作得很好。不能复制:@陌生人!你缺少一个包含守卫吗?两次定义同一个东西会产生错误:答案很好!答案很清楚,给出的解决方案和示例肯定会帮助我,希望未来的读者能够解决这个问题!
// header.h
// No include guard!
bool gatt_db_service_set_active(struct gatt_db_attribute *attrib, bool active, int fd=0);
// ^^ compiler error on this line

// otherheader.h
#include "header.h"

// impl.cpp
#include "header.h"
#include "otherheader.h"

void main()
{} 
// header.h
#ifndef HEADER__H_
#define HEADER__H_

bool gatt_db_service_set_active(struct gatt_db_attribute *attrib, bool active, int fd=0);

#endif // HEADER__H_