我是C ++的初学者(英语为:P),并且我尝试使用SFML进行生活游戏。我创建了具有Application
属性的类EventManager
。我想知道如何从Evenmanager
访问Application
属性。我首先尝试添加一个指向Application
实例的指针,但是我不知道该怎么做。这是正确的方法吗?
编辑:现在我得到了此代码
// Application.h
#ifndef APP_H
#define APP_H
#include "EventManager.h"
class EventManager;
class Application
{
public:
Application(void);
~Application(void);
// ...
private:
EventManager m_eventManager;
};
#endif
// EventManager.h
#ifndef EVENT_MGR_H
#define EVENT_MGR_H
#include "Application.h"
class Application;
class EventManager
{
public:
EventManager::EventManager(Application* app) : m_app(app) {}
~EventManager(void){}
private:
Application* m_app;
};
#endif
Application:m_eventManager uses undefined class EventManager
,这是我唯一的错误。 最佳答案
我提供了一个代码示例,该示例显示并解释了您想要的内容。
编辑:删除了旧示例,在单独的标头中添加了带有类的示例。
Application.hpp:
#ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include "EventManager.hpp" // The EventManager.hpp file is pasted into this header, so it will technically look like the first example I showed.
class Application {
EventManager _event_manager;
public:
Application() : _event_manager(this) {
}
};
#endif
EventManager.hpp
#ifndef EVENT_MANAGER_HPP
#define EVENT_MANAGER_HPP
#include <iostream>
class Application;
class EventManager {
Application* _application;
public:
EventManager(Application* _Application) {
_application = _Application;
std::cout << "Pointer to application: " << _application << std::endl;
}
};
#endif
Main.cpp
#include "Application.hpp"
int main(int argc, char **argv) {
Application application;
std::cin.get();
return (0);
}
关于c++ - 访问“父”对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18016408/