Pointer to array of pointers (dynamic allocation)
I am writing a card game in C++. I have a game class which keeps track of the players. I also have an abstract base class player, from which the classes person and computer derives.
I would like to keep the players in an array. The number of players is unknown at compile time. Because some players are persons and other computers, I need a player pointer for each, stored in an array, which is dynamically allocated because the number of players is unknown, right?
As I am relatively new to C++, I could not figure out how the syntax looks for this kind of thing.
For a dynamic array, the standard library provides std::vector
.
Since you need to store pointers to an abstract base type, rather than the objects themselves, you'll need to make sure you manage the object's lifetimes correctly. The easiest way is to store smart pointers (in this case std::unique_ptr
, for simple single ownership), so that objects are automatically destroyed when they're removed from the vector.
So your array would look like
// Declaration
std::vector<std::unique_ptr<player>> players;
// Adding players
players.push_back(std::unique_ptr<person>(new person("Human"))); // C++11
players.push_back(std::make_unique<computer>("CPU")); // C++14 (hopefully)
// Accessing players
for (auto & player : players) {
player->play();
}
you need
std::vector<std::shared_ptr<Player>> players;
if you want to use the standard library (which you should)
otherwise
Player** players;
You can declare a pointer variable using as the following
Player *playerptr;
It means playerptr is a pointer to type Player.It can hold an address of a Player as well as an array of Players.In C++ and C array is implemented as pointer to the first element of the array.
And as per your requirement you can allocate the array dynamically.
playerptr=new Player[20];
Here 20 is the size of array.
playerptr=new Player[20]();
The second syntax will initialize all the elements in the array to their default value.
链接地址: http://www.djcxy.com/p/72920.html下一篇: 指向数组的指针(动态分配)