如何声明在不同命名空间中定义的结构体?

sam*_*903 5 c++ struct namespaces

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

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

struct DeviceAddress {
    uint8_t systemID;
    uint8_t deviceID;
    uint8_t componentID;
};
Run Code Online (Sandbox Code Playgroud)

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

//File2.c
#include "File1.h"
struct Foo::DeviceAddress bar;
Run Code Online (Sandbox Code Playgroud)

但我在 File2.c 中尝试声明结构的行中收到错误。错误消息是:错误 C2079: 'bar' 使用未定义的结构 'Foo::DeviceAddress'

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

我是否在尝试声明“bar”时犯了某种语法错误,或者我不理解有关命名空间或结构的某些内容?

eml*_*lai 5

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

当您定义名称空间内的结构时,您必须提及其名称空间:

struct Foo::DeviceAddress {
    uint8_t systemID;
    uint8_t deviceID;
    uint8_t componentID;
};
Run Code Online (Sandbox Code Playgroud)

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

namespace Foo{
    struct DeviceAddress {
        uint8_t systemID;
        uint8_t deviceID;
        uint8_t componentID;
    };
}
Run Code Online (Sandbox Code Playgroud)


Bat*_*eba 5

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

namespace Foo {
    struct DeviceAddress {
        uint8_t systemID;
        uint8_t deviceID;
        uint8_t componentID;
    };
}
Run Code Online (Sandbox Code Playgroud)

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