Initiating a derived class with specific variable values
For the below code snippet, how do I initialize instances of class Enemy with variables (such as x, y, type)? I have it working correctly, it triggers the instances no matter how many of them I insert... I just need to know the best way of creating an enemy with certain variables that will differ for each of my instances... particularly when some of those variables are in the base class and others are not.
class BaseObject
{
public:
virtual void Render() = 0;
int x;
int y;
};
class Enemy : public BaseObject
{
public:
Enemy() { }
virtual void Render()
{
cout << "Render! Enemy" << endl;
}
typedef std::set<BaseObject *> GAMEOBJECTS;
GAMEOBJECTS g_gameObjects;
int main()
{
g_gameObjects.insert(new Enemy());
g_lootObjects.insert(new Loot());
for(GAMEOBJECTS::iterator it = g_gameObjects.begin();
it != g_gameObjects.end();
it++)
{
(*it)->Render();
}
for(GAMEOBJECTS::iterator it 开发者_高级运维= g_lootObjects.begin();
it != g_lootObjects.end();
it++)
{
(*it)->Render();
}
return 0;
}
Include the arguments in the enemy constructor and Base constructors. You can then use those to initialize the member variables.
class BaseObject
{
public:
BaseObject(int x, int y) : x(x), y(y){ }
virtual void Render() = 0;
int x;
int y;
};
and
class Enemy : public BaseObject
{
public:
Enemy(int x, int y, int foo) : BaseObject(x,y), foo(foo) { }
int foo;
...
};
精彩评论