克隆对象任意次数

Cloning objects an arbitrary number of times

本文关键字:任意次 对象      更新时间:2023-10-16

我是一名使用SDL2的C++初学者。这是我的问题。

我尝试任意多次克隆同一类的对象,而不必为每个新对象指定特定的名称。

我定义了一个类Enemy1:

class Enemy1
{
public:
//The dimensions of the enemy
static const int Enemy1_WIDTH = 20;
static const int Enemy1_HEIGHT = 20;
//Maximum axis velocity of the dot
static const int Enemy1_VEL = 10;
//Initializes the variables
Enemy1();
//Moves the enemy
virtual void move();
//Shows the enemy on the screen
virtual void render();
private:
//The X and Y offsets of the enemy
int mPosX, mPosY;
//The velocity of the enemy
int mVelX, mVelY;
};

我定义了类中的所有函数,例如:

Enemy1::Enemy1()
{
//Initialize the offsets
mPosX = 320;
mPosY = 240;
//Initialize the velocity
mVelX = 5;
mVelY = 5;
}

然后在我的主循环中:

        //Make first enemy
        Enemy1 enemy1;  
        //While application is running
        while (!quit)
        {
            //Handle events on queue
            while (SDL_PollEvent(&e) != 0)
            {
                //User requests quit
                if (e.type == SDL_QUIT)
                {
                    quit = true;
                }

            //Make more enemies
            if (SDL_GetTicks() > spawnTime)
            {
                    Enemy1 **arbitrary_name_of_copied_enemy**
                    spawnTime = spawnTime + spawnTimeInterval;
            }
        }

我该如何做到这一点而不必说出每个新敌人的名字?这个问题通常是如何处理的?我研究过复制构造函数和克隆,但它们似乎并不能解决这个问题。

如果使用复制构造函数并将其存储在向量或数组中,那么vector.push_back(new Enemy(orig))之类的东西就可以了。