我有一個“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;
};
uj5u.com熱心網友回復:
當你寫道:
struct NPC : Base
{
int gold = 0;
int stats[]; //NOT VALID, this is a definition and size must be known
};
這從cppreference無效:
以下任何背景關系都要求型別 T 是完整的:
- 宣告型別為 T 的非靜態類資料成員;
但是非靜態資料成員的型別stats不完整,因此出現錯誤。
uj5u.com熱心網友回復:
是的,結構可以從類繼承。class 和 struct 關鍵字之間的區別只是默認 private/public 說明符的變化。--> 這里需要指定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;
};
uj5u.com熱心網友回復:
伙計,您不能對結構執行繼承 結構和類之間的主要區別之一是繼承。試試這個
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;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418808.html
標籤:
