How can I make an instant-dependant static variabe in a class method?
I have a function in a class the more or less works like so:
class Player {
private:
Object* minions开发者_运维技巧[16]
public:
void Summon(Object* obj);
};
Player::Summon(Object* obj) {
static int i = 0;
if (i == 16)
return;
minions[i] = obj;
i++;
}
The problem arise when trying to use more than one player, like so:
Player playerone;
Player playerthree;
playerone.Summon(new Object("o1"));
playerthree.Summon(new Object("o2"));
o1
is located in playerone.minions[0]
, as is expected, however, o2
is located in playerthree.minions[1]
, the Summon()
function using the same i
variable. Is there a way to make the Summon()
function use a static i
variable for a single instance, but use separate i
variables for each instance? I know I could do something like make a for
loop to the first spot in minions[]
equal to NULL
, or make i
a member of Player
directly, but I want to know if there is a better way before I do either of those.
Change Object* minions[16];
to a std::vector<Object*> minions;
. That way you can just use minions.size()
to know how many there are, or minions.push_back(obj);
to add one without worrying about array index stuff.
Why don't you simply put i
in each Player
? I'd rename it something like summonned_minion_count
, but that's the actual intent of what you want to do.
Making a local variable static is effectively making it global. You should simply make i
a data member of class Player
. And probably give it a more descriptive name.
You need to make your i
a member variable of Player
.
Or even better you could do something like this:
#include <vector>
class Player {
private:
static int const MAX_MINION_COUNT = 16;
std::vector<Object *> minions;
public:
void Summon(Object* obj) {
if (minions.size() < MAX_MINION_COUNT) {
minions.push_back(obj);
}
}
};
精彩评论