繁体   English   中英

尝试从派生结构 (C++) 继承时出现“无效的基类”错误

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

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

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;
};

当你写道:

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

这从cppreference无效

以下任何上下文都要求类型 T 是完整的:

  • 声明 T 类型的非静态 class 数据成员

但是非静态数据成员stats的类型不完整,因此出现错误。

是的,结构可以从 class 继承。 class 和 struct 关键字之间的区别只是默认私有/公共说明符的变化。 --> 这里需要指定public关键字!

  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;
};

伙计,您不能对结构执行 inheritance 结构和类之间的主要区别之一是 inheritance。 尝试这个

class Base
{
    char* name = 0;

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


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

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

暂无
暂无

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

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