"Invalid base class" 尝试从派生结构继承时出错 (C++)

"Invalid base class" error when trying to inherit from derived struct (C++)

我有一个“Base”结构,一个从“Base”派生的“NPC”结构。一切正常。但是,当我尝试从“NPC”结构创建一个名为“PC”的新结构时,出现错误:“无效基数 class”。 有什么问题?不能从派生结构创建结构吗?

struct Base
{
    char* name = 0;

    int MaxHP = 0;
    int CurrHP = 0;
};


struct NPC : Base
{
    int gold = 0;
    int stats[];
};

struct PC : NPC // I get the error here
{
    unsigned int ID = 0;
};

Yes, a struct can inherit from a class. The difference between the class and struct keywords is just a change in the default private/public specifiers. --> Here you need to specify the public keyword !

  struct Base
{
    char* name = 0;

    int MaxHP = 0;
    int CurrHP = 0;
};


struct NPC : public Base
{
    int gold = 0;
    int stats[];
};

struct PC :  public NPC 
    unsigned int ID = 0;
};

当你写道:

struct NPC : Base
{
    int gold = 0;
    int stats[]; //NOT VALID, this is a definition and size must be known
};

cppreference 开始,无效

Any of the following contexts requires type T to be complete:

  • declaration of a non-static class data member of type T;

但是 non-static 数据成员 stats 的类型不完整,因此出现错误。