2012-12-10 79 views
2

我想寫一個程序來設置一個嵌套結構,然後初始化該結構的數組。這給我一些奇怪的錯誤。這裏的所有相關代碼:如何初始化一個嵌套結構數組

//Structure called Stats for storing initial character stats 
struct Stats{ 
    string name; 
    int level; 
    int HP; 
    int STR; 
    int CON; 
    int DEX; 
    int INT; 
    int WIS; 
    int CHA;}; 

//Structure called Growth for storing character growth per level. 
struct Growth{ 
    int HPperlvl; 
    int STRperlvl; 
    int CONperlvl; 
    int DEXperlvl; 
    int INTperlvl; 
    int WISperlvl; 
    int CHAperlvl;}; 

struct Holdstats{ 
    Stats classstats; 
    Growth classgrowth;}; 

const int SIZE = 10; 

Holdstats classlist[SIZE]; 

Holdstats charlist[SIZE]; 

//Define initial classes, to be stored in the Classes structure 
classlist[0].classstats = {"Fighter", 1, 18, 10, 10, 10, 10, 10, 10}; 
classlist[0].classgrowth = {1,1,1,1,1,1,1}; 

classlist[1].classstats = {"Wizard", 1, 10, 10, 10, 10, 10, 10}; 
classlist[1].classgrowth = {1,1,1,1,1,1,1} 

我的編譯器認爲,當我鍵入「班級列表[0] .classstats」我試圖初始化大小爲0的數組我看這個問題的方法,我想訪問類列表數組的第一個元素。這寫的是否正確?

如果有人能給我一個這樣一個數組的樣子的簡短例子,那將是很棒的。從那裏我想寫它作爲一個載體

+0

甚至沒有讀過這個問題,但是你需要在結構聲明之後有一個分號。 – gsingh2011

+0

是的,我注意到,壞複製粘貼錯誤哈哈。 –

回答

2

你沒有顯示你所有的類型,但你應該能夠採取這種基本的方法。

Holdstats classlist[SIZE] = { 
    { {"Fighter", 1, 18, 10, 10, 10, 10, 10, 10}, {1,1,1,1,1,1,1} }, 
    { {"Wizard", 1, 10, 10, 10, 10, 10, 10}, {1,1,1,1,1,1,1} }, 
} 
+0

謝謝!我不知道你可以這樣做。這解決了我的問題,但我仍然對我爲什麼首先得到錯誤感興趣。 –

+0

@DustinBurns:我甚至沒有看到您發佈錯誤的位置。 –

0

您的結構Holdstats擁有classstatsclassgrowth類型的兩個其他結構。請記住這些結構,不是數組,所以我不會完全知道爲什麼你給它們像這樣:

classlist[0].classstats = {"Fighter", 1, 18, 10, 10, 10, 10, 10, 10}; 

我猜你要填寫統計結構內holdstats結構本身,這將在下面進行:

classlist[0].classstats.health = 15; //guessing you have a member named health 
//OR if you create a constructor for you classstats with the proper copy constructor 
classlist[0].classstats = classstats("Fighter", 1, 18, 10, 10, 10, 10, 10, 10); 
//OR if you have an assign function 
classlist[0].classstats.assign("Fighter", 1, 18, 10, 10, 10, 10, 10, 10); 
+0

它仍然像我輸入classlist [0] .classstats時那樣操作,我嘗試初始化一個大小爲0的數組而不是訪問數組的第一個元素。任何想法如何解決這個問題?非常感謝,但我想我得到爲什麼我必須這樣做 –

+0

告訴我們你的其他結構,錯誤可能在於這些 –