【问题标题】:How to declare struct defined in different namespace?如何声明在不同命名空间中定义的结构?
【发布时间】:2016-01-13 23:01:28
【问题描述】:

我在使用在不同命名空间中声明的结构时遇到问题。在 File1.h 中,我声明了结构并将其放在命名空间“Foo”中。

//File1.h
namespace Foo{
    struct DeviceAddress;
}

struct DeviceAddress {
    uint8_t systemID;
    uint8_t deviceID;
    uint8_t componentID;
};

在 File2.c 中,我尝试创建该结构的实例:

//File2.c
#include "File1.h"
struct Foo::DeviceAddress bar;

但我在 File2.c 中尝试声明结构的那一行出现错误。错误信息是: 错误 C2079:'bar' 使用未定义的结构 'Foo::DeviceAddress'

我使用 MS C++ 编译器和 Visual Studio 作为开发环境。

我是在尝试声明“bar”时出现某种语法错误,还是我不了解命名空间或结构?

【问题讨论】:

  • 你必须声明你的struct 驻留在这个命名空间中。前向声明不足以使其进入Foo。

标签: c++ struct namespaces


【解决方案1】:

File1.h 中的两个DeviceAddresses不是同一个结构:一个在命名空间Foo 内,另一个在全局命名空间内。

在命名空间内定义结构时,必须提及其命名空间:

struct Foo::DeviceAddress {
    uint8_t systemID;
    uint8_t deviceID;
    uint8_t componentID;
};

或者简单地同时声明和定义它,这是推荐的方式:

namespace Foo{
    struct DeviceAddress {
        uint8_t systemID;
        uint8_t deviceID;
        uint8_t componentID;
    };
}

【讨论】:

    【解决方案2】:

    问题出在struct 的定义中:它也需要在命名空间中定义:

    namespace Foo {
        struct DeviceAddress {
            uint8_t systemID;
            uint8_t deviceID;
            uint8_t componentID;
        };
    }
    

    您当前正在全局命名空间中定义一个单独的Foo。

    【讨论】:

      猜你喜欢
      • 2017-06-01
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 2015-05-10
      • 2020-12-03
      • 2014-08-16
      • 1970-01-01
      • 2010-10-27
      相关资源
      最近更新 更多