声明结构体或联合体成员的正确语法是什么?

问题描述 投票:0回答:1

长话短说,我从 Sony PlayStation .SYM 符号文件生成标头。

当我使用 Visual Studio Code 测试语法的有效性时,我得到以下信息:

标签类型的联合与“PacketData”类的声明不兼容

示例:

struct PacketData
{
    short Data[2];
    unsigned long Control;
};

struct Packet
{
    unsigned char CheckSum;
    char Action;
    short Padw;
    union PacketData Data; // tag kind of union is incompatible with declaration of class "PacketData"
};

这个问题似乎可以通过在

union
之前删除
PacketData
来解决。

这是由

DUMPSYM.EXE
命令行实用程序输出的结构:

02cc47: $00000000 94 Def class STRTAG type STRUCT size 8 name Packet
02cc5b: $00000000 94 Def class MOS type UCHAR size 0 name CheckSum
02cc71: $00000001 94 Def class MOS type CHAR size 0 name Action
02cc85: $00000002 94 Def class MOS type SHORT size 0 name Padw
02cc97: $00000004 96 Def2 class MOS type UNION size 4 dims 0 tag PacketData name Data
02ccb6: $00000008 96 Def2 class EOS type NULL size 8 dims 0 tag Packet name .eos

但是,为什么结构体成员可以可选地具有

struct
前缀?

struct Sprite
{
    unsigned char X;
    unsigned char Y;
    unsigned short Page;
    unsigned char SWidth;
    unsigned char SHeight;
    unsigned short Clut;
};

struct SpriteData
{
    struct Sprite *Sprites;
    struct Sprite *EndSprites;
    unsigned long Data;
};

您能否澄清如何声明此类成员?

c struct syntax unions
1个回答
0
投票

您已经定义了

struct PacketData
,后来尝试创建类型为
union PacketData
的变量/成员。这是两种不同的类型。

您收到的具体错误消息表明您正在使用 C++ 编译器进行编译。在 C++ 中,您可以创建

struct
union
的实例,而无需使用相应的关键字。这也意味着在 C++ 中,您无法创建同名的
struct
union
,这就是错误消息告诉您的内容。

鉴于您发布的转储告诉您

PacketData
union
,您应该将其定义为该类型:

union PacketData
{
    short Data[2];
    unsigned long Control;
};

如果您的代码实际上是 C 语言,那么您应该使用 C 编译器进行编译。如果这恰好是 MSVC,则意味着您的源文件需要有 .c 扩展名。

© www.soinside.com 2019 - 2024. All rights reserved.