0

对于下面的代码片段,如何使用变量(例如 x、y、type)初始化类 Enemy 的实例?我让它正常工作,无论我插入多少个实例,它都会触发实例......我只需要知道使用某些变量创建敌人的最佳方法,这些变量对于我的每个实例都会有所不同......特别是当一些这些变量中的一个在基类中,而其他变量不在。

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

1 回答 1

4

在敌人构造函数和 Base 构造函数中包含参数。然后,您可以使用它们来初始化成员变量。

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

class Enemy : public BaseObject
{
public:

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

    int foo;
...
};
于 2011-03-16T18:34:54.037 回答