2016-11-13 66 views
2

我想將我的項目分成更小的部分,導致它開始無法讀取(1000多行),並且我指定的.h和.cpp有一些問題需要使用定義的定義其他文件。劃分項目爲.h和.cpp

項目包含以下文件:

的main.cpp RPG.h和.cpp Hero.h和.cpp Globaldefs.h和.cpp以上

#ifndef Hero_h 
#define Hero_h 
#include "Globaldefs.h" 
#include "RPG.h" 
#include <vector> 

using namespace std; 

extern class NPC; 
extern class Inventory; 

class Hero 
{ 
protected: 
    (...) 
    Inventory inventory; 
    (...) 
public: 
    vector<Mob*>::iterator TryAttack(vector <Mob*>& monsters, int & number); 
    vector<NPC*>::iterator TryTalk(vector <NPC*>& _NPCs, int & number); 

}; 
(...) 
#endif 

聲明是英雄。 h文件和彙編器在行庫存盤點中發現錯誤; (該類在外部,在RPG.h中聲明並在RPG.cpp中定義):'Hero :: inventory'使用未定義的類'Inventory'RPG d:\ programming \ rpg \ rpg \ rpg \ hero.h 23我完全不會不明白爲什麼Mob(RPG.h和.cpp中的其他類)正常工作,NPC也定義爲extern(也在RPG.h中)。

#ifndef RPG_h 
#define RPG_h 
#include "Globaldefs.h" 
#include "Hero.h" 
#include <vector> 

using namespace std; 

class Mob; 
class NPC; 
class Fight; 
class Item; 
extern class Hero; 
(...) 
class Meat : public Item 
{ 
(...) 
public: 
    virtual void ActivateEffect(Hero* _hero) { _hero->AddHp(15); }; 
}; 
#endif 

這是RPG.h文件,並在那裏,compilator說,出事了符合

virtual void ActivateEffect(Hero* _hero) { _hero->AddHp(15); }; 

有:使用未定義的類型 '英雄' RPG d的:\程序\ RPG \ rpg \ rpg \ rpg.h 97和左側的' - > AddHp'必須指向class/struct/union/generic類型RPG d:\ programming \ rpg \ rpg \ rpg \ rpg.h 97

我收藏了很多但是到處都有人向簡單的向main.cpp添加文件的問題,而不是在文件之間建立內部連接。

+0

的main.cpp RPG.h和.cpp Hero.h和.cpp Globaldefs.h和.cpp這顯然不是部分代碼:d fckin編輯不要讓我張貼的問題沒有標記那些爲代碼 –

回答

3

包含警告阻止您在Hero.h中包含RPG.h,反之亦然。

你所做的就是轉發declare Hero in RPG.h,這很好。

但你做的事:

virtual void ActivateEffect(Hero* _hero) { _hero->AddHp(15); }; 

和編譯器需要知道Hero類的結構,它鏈接到AddHp方法。你不能那樣做。

做那,而不是(只申報法):

virtual void ActivateEffect(Hero* _hero); 

,並刪除了#include "Hero.h"線。

然後在RPG.cpp文件做:

#include "Hero.h" 
void RPG::ActivateEffect(Hero* _hero) { _hero->AddHp(15); } 

我們看不到的Inventory問題的代碼,但是我想這是同樣的問題。

總結:

  • 可以包括文件A.h文件B.h但在這種情況下,你不能包含文件B.hA.h
  • ,但你可以轉發在A.h聲明class B和參考指針/參考該類,只要您不嘗試在頭文件中使用B方法。
  • 使用B方法A對象,只包括A.cppB.h並在A.cpp訪問所有B方法。一些內聯方法不能在.h文件來實現,當他們使用的B
1

你有RPG.h和Hero.h和RPG.h線97之間的循環依賴,只有向前聲明方法/成員(extern class Hero;)是可見的,因此您只能引用指針和對整個Hero對象的引用,並且不能引用成員Hero

在任何情況下,循環依賴本身都可能表示設計不佳。