Yet another C++ list question
Im quite stuck here and I have tried my best but I could not solve it.
I would like to do this:
list<Enemy> *_myEnemies;
Enemy* _myEnemiesPushBack;
_myEnemiesPushBack = new Enemy;
_myEnemiesPushBack->load("earth.png");
_myEnemiesPushBack->setPos(150, 150);
_myEnemies->push_back(_myEnemiesPushBack); //error here
The error:
\init.cpp(41): error C2664: 'void std::list<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'Enemy *' to 'Enemy &&a开发者_如何学编程mp;' 1> with 1> [ 1> _Ty=Enemy 1>
] 1> Reason: cannot convert from 'Enemy *' to 'Enemy' 1> No constructor could take the source type, or constructor overload resolution was ambiguous
Thanks!
You don't need pointers, at all.
std::list<Enemy> myList;
Enemy en;
en.load("earth.png");
en.setPos(150,150);
myList.push_back(en);
typedef std::list<Enemy>::iterator iterator;
for (iterator it = list.begin(), end = list.end(); it != end; ++it) {
it->move();
}
I would also encourage you to fetch a book about C++ somewhere (for beginners), or about the STL if it's your particular hurdle. C++ is not, unfortunately, something you can experiment with without guidance (at first at least).
You misplaced a *
list<Enemy*> _myEnemies;
Enemy* _myEnemiesPushBack;
_myEnemiesPushBack = new Enemy;
_myEnemiesPushBack->load("earth.png");
_myEnemiesPushBack->setPos(150, 150);
_myEnemies.push_back(_myEnemiesPushBack); //error here
You've got a list of Enemy's and are trying to push a pointer to an Enemy into that list. They're not the same type.
Take a look here: Pointers @ cplusplus
精彩评论