开发者

Initiating a derived class with specific variable values

开发者 https://www.devze.com 2023-02-17 10:10 出处:网络
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

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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号