2012-09-23 127 views
-1

我得到了我的主類遊戲C++類艾策斯陣列陣列從其他類

Galaxian.h:

class Galaxian{ 
public: 
    void update(); 
}; 

Galaxian.cpp:

這是我的問題:我想從遊戲類訪問galaxians數組,但我不知道如何!當我嘗試遊戲:: galaxians時,出現錯誤「非靜態成員參考必須是相對於特定對象的」

我想完成的是我可以循環槽數組並更改每個鍵的值它。

我該怎麼做?

回答

1

static成員綁定到一個類的實例,而不是類本身。這是通用的面向對象,不是C++特有的。讓你無論是綁定訪問對象,或成員到類:

Game g;  //create an object of the class 
g.galaxians; //access the member through the object 

class Game{ 
public: 
    static Galaxian galaxians[6][10]; //bind the member to the class 
}; 

//... 

Game::galaxians; //access it through the class 

你選擇哪一個取決於你的邏輯。

2

這是因爲galaxians成員是實例成員,而不是類(即非靜態)成員。您應該(1)在需要訪問galaxians的位置提供Game的實例,或者(2)使galaxians成爲靜態成員。

如果您決定第一種方式,考慮製作Game a 單身人士;如果您決定採用第二種方式,請不要忘記在cpp文件中定義您的galaxians數組,除了在頭文件中聲明它static

1

您需要訪問的Game一個實例:

Game g; 
g.galaxians[3][4] = ....;