How can I keep track of when new instances are made?
I'm trying to see what kind of things you can do with Instances of classes and stuff, and for a piece in my game, I want to know how I can store any Instances of the Enemy class into a vector. Like Enemy Dark_Lord; then using GetName(); I can store the name of that enemy instance. Is it possible to do this? If so, how would I get started on implementing it?
if i correctly understand you, you want to have a vector and you sorta want to do a "enemy_vector["evil lord"]" call and get the class of that enemy. If that is so you can do a map.
You can completely disregard this post if this is not what your talking about...
You could create a singleton class (one where only a single instance may exist) that "manages" your enemy class. Everytime you create an enemy, you could register it with your "manager" class inside your enemy class constructor.
How you store each enemy in your manager class is up to you. I.e you could use a map as suggested above, or you could use a vector - easier to test i guess, but less efficient if many enemies will exist.
Now if you want to extract the names of all your enemies, you could supply a method in the manager class that does this for you. This method could use an iterator to cycle through your vector/map calling a "getName()" method on each enemy object.
I hope this helps.
You could create a singleton class (one where only a single instance may exist) that "manages" your enemy class. Everytime you create an enemy, you could register it with your "manager" class inside your enemy class constructor.
How you store each enemy in your manager class is up to you. I.e you could use a map as suggested above, or you could use a vector - easier to test i guess, but less efficient if many enemies will exist.
Now if you want to extract the names of all your enemies, you could supply a method in the manager class that does this for you. This method could use an iterator to cycle through your vector/map calling a "getName()" method on each enemy object.
I hope this helps.
class Enemy{ public: Enemy(const string &name); // inside implementation register this with the enemy manager};typedef vector<Enemy*> EnemyList;class EnemyManager{ private: static EnemyList enemies; public: static Enemy* FindEnemy(const string &name);};
thats just one possible shape, there are definately many little choices you can do a lot differently ... for instance I would usually write the EnemyManager as a non-static normal class and then have a seperate static / singleton instance to be used by default ... but those are just details. There are many ways to skin this cat, and either way its not going to like it :)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement