2013-08-02 157 views
0

我是C++初學者(英文爲:P),我嘗試着用SFML打造生活遊戲。我使用EventManager屬性創建了一個類Application。我想知道如何訪問從EvenmanagerApplication屬性。我首先嚐試添加一個指向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,這是我唯一的錯誤。

+4

我認爲這是很好的添加一些代碼。 – user2029077

+3

如果您編輯您的問題以顯示您所嘗試的內容,我相信有人可以幫助指出您所犯的錯誤以及如何修復這些錯誤。 –

+0

我剛加入它 – palra

回答

4

我已經包含了一個代碼示例,顯示並解釋你想要什麼。

編輯:刪除舊的例子,添加這個例子與類在單獨的頭。

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); 
} 
+0

我剛剛更新了我的代碼,仍然不起作用... – palra

+0

我已更新答案。它現在使用兩個獨立的頭文件,就像你的代碼一樣。 – 2013-08-02 12:59:44

+0

哦,謝謝!我只需要移除EventManager.h中的#include「Application.h」來解決問題:) – palra

1

你在你的頭有一個循環依賴關係:每個嘗試包括其他。包含警衛意味着每個只包含一次,但一個定義會出現在另一個之前。在這種情況下,最後在EventManager之前定義的Application;這是不好的,因爲它需要定義EventManager以聲明成員變量。

幸運的是,EventManager不需要Application的完整定義,因爲它只使用指向該類型的指針;所以你可以刪除#include "Application.h",只是離開聲明class Application;