我得到了我的主類遊戲C++類艾策斯陣列陣列從其他類
Galaxian.h:
class Galaxian{
public:
void update();
};
Galaxian.cpp:
這是我的問題:我想從遊戲類訪問galaxians數組,但我不知道如何!當我嘗試遊戲:: galaxians時,出現錯誤「非靜態成員參考必須是相對於特定對象的」
我想完成的是我可以循環槽數組並更改每個鍵的值它。
我該怎麼做?
我得到了我的主類遊戲C++類艾策斯陣列陣列從其他類
Galaxian.h:
class Galaxian{
public:
void update();
};
Galaxian.cpp:
這是我的問題:我想從遊戲類訪問galaxians數組,但我不知道如何!當我嘗試遊戲:: galaxians時,出現錯誤「非靜態成員參考必須是相對於特定對象的」
我想完成的是我可以循環槽數組並更改每個鍵的值它。
我該怎麼做?
非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
你選擇哪一個取決於你的邏輯。
這是因爲galaxians
成員是實例成員,而不是類(即非靜態)成員。您應該(1)在需要訪問galaxians
的位置提供Game
的實例,或者(2)使galaxians
成爲靜態成員。
如果您決定第一種方式,考慮製作Game
a 單身人士;如果您決定採用第二種方式,請不要忘記在cpp文件中定義您的galaxians
數組,除了在頭文件中聲明它static
。
您需要訪問的Game
一個實例:
Game g;
g.galaxians[3][4] = ....;