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

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

本文关键字:class base 错误 C++ Invalid 派生 结构 继承      更新时间:2024-09-22

我有一个"基本;结构,一个";NPC";结构派生自";基本";。一切都很好。但是当我尝试创建一个名为";PC";从";NPC";结构,我得到一个错误:";无效基类";。怎么了?是否不能从派生结构创建结构?

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的非静态类数据成员的声明

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

是的,结构可以从类继承。类关键字和结构关键字之间的区别只是默认的私有/公共说明符的变化。-->这里你需要指定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;
};
相关文章: