我正在通過做一個小型機器人模擬來學習C++,而且我在類內靜態成員函數時遇到了問題。C++靜態成員函數和變量
我已經定義是這樣我的環境類:
class Environment {
private:
int numOfRobots;
int numOfObstacles;
static void display(); // Displays all initialized objects on the screen
public:
Robot *robots;
Obstacle *obstacles;
// constructor
Environment();
static void processKeySpecialUp(int, int, int); // Processes the keyboard events
};
然後在構造函數中我初始化機器人和障礙是這樣的:
numOfRobots = 1; // How many robots to draw
numOfObstacles = 1;
robots = new Robot[numOfRobots];
obstacles = new Obstacle[numOfObstacles];
這裏是例如靜態函數的使用這些變量:
void Environment::display(void) {
// Draw all robots
for (int i=0; i<numOfRobots; i++) {
robots[i].draw();
}
}
當我嘗試編譯時,收到錯誤消息如
error: invalid use of member ‘Environment::robots’ in static member function
我試圖使numOfRobots,numOfObstacles,機器人和障礙靜態,但後來我得到了這樣的錯誤
error: undefined reference to 'Environment::numOfRobots'
我將不勝感激有人可以解釋我什麼我做錯了。 謝謝!
在你的代碼的靜態版本中,你沒有定義'Environment :: numOfRobots',你只聲明瞭它。將'int Environment :: numOfRobots = 1;'添加到其中一個源文件中。一本關於C++的書將解釋如何聲明和定義變量以及其他重要信息。 – john
既然你說你正在學習C++,我可以建議使用標準庫嗎?特別是'std :: vector'而不是原始數組。 – bitmask