I want my Bullet class to have access to a list of Ship, so I have a static variable that is a pointer to the list object.
class Bullet {
...
static list<Ship*>* enemyList;
...
}
Declaring the list,
std::list<Ship*> enemyList;
Finally, I provide the definition for my static variable:
std::list<Ship*>* Bullet::enemyList = &enemyList;
However, the compiler gives the following error:
error: cannot convert `std::list<Ship*, std::allocator<Ship*> >**' to `std::list<Ship*, std::allocator<Ship*> >*' in initialization|
By changing my definition to the following, the program compiles but segfaults when the function requiring the list is called:
std::list<Ship*>* Bullet::enemyList = enemyList; //no &
Which leads me to believe that there is an error in my understanding and usage of std::list, but I'm not sure what that is. Thanks!
EDIT : Resolved
As pointed out by Matt McNabb below, enemyList on the right hand side of
std::list<Ship*>* Bullet::enemyList = &enemyList;
referenced the enemyList on the left hand side rather than the enemyList I wanted to call outside of the class. Using distinct names solved this issue.
Firstly it sounds like you want:
static list<Ship> enemyList;
It's not clear why you want pointers to be involved. If you use this form then all your other questions are rendered moot, but to answer it anyway:
This line makes no sense:
std::list<Ship*>* Bullet::enemyList = &enemyList;
You're trying to initialize the list to point to itself, which is not possible (since the list contains Ship*
, not list<Ship*>
). The declaration would be:
list<Ship*> *Bullet::enemyList;
and you would also have to make that pointer point somewhere (by default it will be a null pointer).
Your second version compiles but it is just like writing:
int x = x;
hopefully you can understand why this is a problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.