使用特定变量值启动派生类

发布于 2024-10-23 13:31:56 字数 892 浏览 5 评论 0原文

对于下面的代码片段,如何使用变量(例如 x、y、类型)初始化类 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;
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

比忠 2024-10-30 13:31:56

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

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

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;
...
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文