Initiating a derived class with specific variable values

本小妞迷上赌 提交于 2019-12-11 16:57:47

问题


For the below code snippet, how do I initialize instances of class Enemy with variables (such as x, y, type)? I have it working correctly, it triggers the instances no matter how many of them I insert... I just need to know the best way of creating an enemy with certain variables that will differ for each of my instances... particularly when some of those variables are in the base class and others are not.

class BaseObject
{
public:
    virtual void Render() = 0;
    int x;
    int y;
};

class Enemy : public BaseObject
{
public:

    Enemy() { }
    virtual void Render()
    {
        cout << "Render! Enemy" << endl;
    }

typedef std::set<BaseObject *> GAMEOBJECTS;
GAMEOBJECTS g_gameObjects;

int main()
{
    g_gameObjects.insert(new Enemy());

    g_lootObjects.insert(new Loot());

    for(GAMEOBJECTS::iterator it = g_gameObjects.begin();
    it != g_gameObjects.end();
    it++)
    {
        (*it)->Render();
    }

    for(GAMEOBJECTS::iterator it = g_lootObjects.begin();
        it != g_lootObjects.end();
        it++)
    {
        (*it)->Render();
    }

    return 0;
}

回答1:


Include the arguments in the enemy constructor and Base constructors. You can then use those to initialize the member variables.

class BaseObject
{
public:
    BaseObject(int x, int y) : x(x), y(y){ }
    virtual void Render() = 0;
    int x;
    int y;
};

and

class Enemy : public BaseObject
{
public:

    Enemy(int x, int y, int foo) : BaseObject(x,y), foo(foo) { }

    int foo;
...
};


来源:https://stackoverflow.com/questions/5330020/initiating-a-derived-class-with-specific-variable-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!