c++ - 动态创建对象并将它们添加到链表中

标签 c++ list dynamic linked-list

这是一款 C++ 控制台游戏,其中包含发射炮弹的坦克。问题出在坦克外壳部分。 我想创建一个 PlayerTankShell 类的对象,并在每次按下空格键时将其添加到链表中。我该怎么做?

这是我的代码:

#include <iostream>
#include <conio.h>
#include <list>

using namespace std;

#define ATTACK  32

class PlayerTankShell
{
    int x;
    int y;
    int speed;
    bool isExist;

public:
    PlayerTankShell(bool exists)
    {
        isExist = exists;
    }
    bool getExistense()
    {
        return isExist;
    }
};

int main()
{
    char input;
    input = getch();

    if (input == ATTACK)
    {
        // Here create an object and add it to the linked list
    }

    // My test so far:
    PlayerTankShell *s1 = new PlayerTankShell(1);
    PlayerTankShell *s2 = new PlayerTankShell(1);
    PlayerTankShell *s3 = new PlayerTankShell(1);

    list<PlayerTankShell> listShells;

    listShells.push_back(*s1);
    listShells.push_back(*s2);
    listShells.push_back(*s3);

    list<PlayerTankShell>::iterator i;

    for (i = listShells.begin(); i != listShells.end(); i++)
    {
        cout << "exists=" << i->getExistense() << endl;
    }

    return 0;
}

最佳答案

你想要这样的东西:

std::list<PlayerTankShell> shells;

然后你可以添加:

shells.push_back(PlayerTankShell(true))

关于c++ - 动态创建对象并将它们添加到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12746866/

相关文章:

c++ - 仅当首先复制到临时变量中时,传递对字符串的引用才有效

python - 'cv::Point2f&' 类型的非常量引用的初始化无效

java - 返回最大尺寸的列表<integer>对象

javascript - HTML 和 Javascript 在 POST 表单值之前修改

c# - 是否可以使用 ExpandoObject 创建动态树结构?

c# - 这是对泛型和 C# 的动态数据类型的适当使用吗?

c++ - 使用 Qt 和 Opengl 强制注销崩溃

c++ - 具有 const cv::Mat 类型的参数在功能上会发生变化吗?

r - 如何 rbind 包含在 R 子列表中的 data.frames

c++ - STL List 复制一个结构,但复制的值偏移了两个内存地址