0

以下のコード スニペットでは、Enemy クラスのインスタンスを変数 (x、y、type など) で初期化するにはどうすればよいですか? 私はそれが正しく機能しています。挿入したインスタンスの数に関係なく、インスタンスをトリガーします...インスタンスごとに異なる特定の変数を使用して敵を作成する最良の方法を知る必要があります...特にいくつかの場合これらの変数のうち、基本クラスにあるものとそうでないものがあります。

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

引数を敵のコンストラクターとベース コンストラクターに含めます。その後、それらを使用してメンバー変数を初期化できます。

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 に答える