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

Default parameter given for parameter X of function Y

本文关键字:参数 默认 函数      更新时间:2023-10-16

我正在尝试为这个函数声明中的参数分配一个默认值:

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

然而,我得到错误

为"bool gatt_db_service_set_active(gatt_db_attribute*,bool,int)"[-fpermission]的参数3给定的默认参数

然后它说:

"bool gatt_db_service_set_active(gatt_db_attribute*,bool,int)"中的先前规范,此处:bool gatt_db_service_set_active(结构gatt_db_attribute*attrib,bool active,int fd;<

它指向相同的函数声明。

这就是定义:

bool gatt_db_service_set_active(struct gatt_db_attribute *attrib, bool active, int fd) 
{
    //stuff
}

正如你所看到的,我没有设置两次默认参数,这是关于这个错误的大多数问题的问题。我在Ubuntu 15.1 上用gcc version 5.2.1编译这个

有人知道这里发生了什么吗?

如果您以某种方式声明了函数两次(这样编译器就会看到两行类似的代码):

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

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

... A default argument shall not be redefined by a later declaration.

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

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

// 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_

这将防止header.h的第二个(以及随后的)包含两次声明相同的东西。

事实证明,在我声明函数的标头中没有标头保护。

我发现错误指向自己很奇怪,所以我试图通过在顶部添加#ifndef FOO#define FOO以及在底部添加#endif这样的头保护来解决它。这起到了作用。

感谢Inductiveload的指针!