这是一款 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/