我正在通过制作一个小型机器人模拟来学习C ++,但是我在类内使用静态成员函数时遇到了问题。
我的Environment类的定义如下:
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、robots 和 obstacles 声明为 static 变量,但是出现了以下错误:
error: undefined reference to 'Environment::numOfRobots'
如果有人能够解释我做错了什么,我将非常感激。 谢谢!
Environment::numOfRobots
,而只是声明了它。请在其中一个源文件中添加int Environment::numOfRobots = 1;
。一本关于C++的书籍将会解释如何声明和定义变量以及其他重要信息。 - johnstd :: vector
而不是原始数组。 - bitmask