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

时间:2016-01-05 11:44:37

标签: c++ parameters

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

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

然而,我收到错误

  

为参数3提供的默认参数' bool gatt_db_service_set_active(gatt_db_attribute *,bool,int)' [-fpermissive]

然后它说:

  

以前的规范' bool gatt_db_service_set_active(gatt_db_attribute *,bool,int)'这里:    bool gatt_db_service_set_active(struct gatt_db_attribute * attrib,bool active,int fd;<

哪个指向相同的函数声明。

这是定义:

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

正如您所看到的,我没有将默认参数设置两次,因为大多数有关此错误的问题都存在问题。我正在使用gcc version 5.2.1

上的Ubuntu 15.1进行编译

有谁知道这里发生了什么?

2 个答案:

答案 0 :(得分:4)

事实证明,我在宣布该功能的标题中没有标题保护。

我发现奇怪的是错误指向了自己,所以我尝试通过简单地在顶部添加#ifndef FOO#define FOO以及底部的#endif来解决此问题。这很有效。

感谢Inductiveload指针!

答案 1 :(得分:4)

如果你以某种方式声明了该函数两次(以便编译器看到两行这样的代码):

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.

example code演示了错误。请注意,如果您不重新定义默认值,可以多次声明一个函数,这可能对前向声明有用。

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

// 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的第二次(及后续)包含两次声明相同的内容。