C ++静态成员函数和变量 [英] C++ static member functions and variables

查看:59
本文介绍了C ++静态成员函数和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过进行小型机器人仿真来学习C ++,但是在类内部使用静态成员函数时遇到了麻烦.

I am learning C++ by making a small robot simulation and I'm having trouble with static member functions inside classes.

我的环境类定义如下:

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
};

然后在构造函数中,我像这样初始化机器人和障碍物:

Then in the constructor I initialize the robots and obstacles like this:

numOfRobots = 1; // How many robots to draw
numOfObstacles = 1;
robots = new Robot[numOfRobots];
obstacles = new Obstacle[numOfObstacles];

以下是使用这些变量的静态函数的示例:

Here is example of static function that uses those variables:

void Environment::display(void) {
    // Draw all robots
    for (int i=0; i<numOfRobots; i++) {
        robots[i].draw();
    }
}

当我尝试编译时,出现类似错误消息

When I try to compile, I get error messages like

error: invalid use of member ‘Environment::robots’ in static member function

我尝试制作静态的numOfRobots,numOfObstaclecles,机器人和障碍物,但是随后出现类似错误

I tried making numOfRobots, numOfObstacles, robots and obstacles static, but then I got errors like

error: undefined reference to 'Environment::numOfRobots'

我非常感谢有人可以向我解释我做错了什么.谢谢!

I would greatly appreciate of someone could explain me what I am doing wrong. Thank you!

推荐答案

静态方法不能使用其类中的非静态变量.

Static methods can't use non-static variables from its class.

这是因为可以在没有类实例的情况下像 Environment :: display()那样调用静态方法,这会使其中使用的任何非静态变量不规则,也就是说,它们不会没有父对象.

That's because a static method can be called like Environment::display() without a class instance, which makes any non-static variable used inside of it, irregular, that is, they don't have a parent object.

您应该考虑为什么要为此目的使用静态成员.基本上,如何使用静态方法的一个示例如下:

You should consider why you are trying to use a static member for this purpose. Basically, one example of how a static method can be used is as such:

class Environment
{
private:
    static int maxRobots;
public:
    static void setMaxRobots(int max)
    {
        maxRobots = max;
    }
    void printMaxRobots();
};

void Environment::printMaxRobots()
{
    std::cout << maxRobots;
}

您将必须在全局范围内初始化变量,例如:

And you would have to initialize on the global scope the variables, like:

int Environment::maxRobots = 0;

然后,例如在 main 内部,您可以使用:

Then, inside main for example, you could use:

Environment::setMaxRobots(5);

Environment *env = new Environment;
env->printMaxRobots();
delete env;

这篇关于C ++静态成员函数和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆