繁体   English   中英

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

[英]How to declare struct defined in different namespace?

我在使用在其他名称空间中声明的结构时遇到了麻烦。 在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'

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

我在尝试声明“ bar”时是否犯了某种语法错误,还是不了解有关名称空间或结构的某些知识?

File1.h中的两个DeviceAddress 不是相同的结构 :一个位于名称空间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;
    };
}

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM