开发者

Call function from object instantiated in one class in another

I have two classes, both of which need t开发者_如何学Co be able to call the same instance of entitymanager

class Engine
{
  EntityManager::Entitymanager EManager;
}

And I need to add an object to a vector contained by this particular instance of Engine. What I want to do is be able to add a bullet spawned by the player to the vector that contains all my entities.

class Player : Entity
{
  void SpawnBullet() {Engine::EManager.Add(BULLET);}
}

The above returns this error:

error: object missing in reference to ‘Engine::EManager’

How do I resolve this? Any help or pointers in the right direction would be much appreciated!


You are trying to access EManager without a class instance associated with it.

There are 2 solutions for this.

You have to have an instance of Engine around in order to access EManager:

class Engine {
    EntityManager::Entitymanager EManager;
};

Then you can access EManager this way:

m_engine.EManager.Add(BULLET)

You have to make EManager a static member of Engine (that is, it will be bound to the class scope only, you won't need an instance for it):

class Engine {
public:
    static EntityManager::Entitymanager EManager;
};

Then you can access it as you already did (It has to be public, or your classes have to be friends).

I feel however that you need to get a good introductory C++ book and understand what you are trying to achieve. And while you're at it, get one on software engineering too ;).


I have two classes, both of which need to be able to call the same instance of entitymanager

It seems you need to implement Singleton pattern. Have a look at the link, maybe you'll have a good design of your classes!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜