2011-11-26 66 views
0

爲什麼當我試圖通過這樣的一個指針創建一個屬性到另一個類我收到一個錯誤:指向另一個類的屬性

#ifndef SQUARE_H 
#define SQUARE_H 

#include <string> 
//using namespace std; 

    #include "Player.h" 

class Square 

{ 
public: 

    Square(int); 
    void process(); 

protected: 

    int ID; 
    Player* PlayerOn;   <--- 

}; 



    #endif 

和Player類是:

#ifndef PLAYER_H 
    #define PLAYER_H 

    #include <string> 
//using namespace std; 

    #include "Square.h" 

class Player 
{ 
public: 

    Player(int,int); 
// ~Player(void); 
    int playDice(); 


private: 

     int ID; 
     int money; 


}; 
#endif 

我收到:

syntax error missing ; before * (on the declaration of Player* PlayerOn;) 

和缺少類型說明符(在同一行...)

+1

您的文章傷害了我的眼睛,您是否可以將每個文件的代碼放入代碼塊中,而不是將它們分成幾個? –

+2

爲什麼你在Player.h中包含Square.h? – Mark

+0

@標記這是他錯誤的原因(由於#ifdef),你可能想把它放在答案:) –

回答

2

的問題是,你是在Player.h inclding Square.h,所以當你得到Player* PlayerOn;球員沒有定義

要麼沒有在你的Player.h的#include "Square.h"將與合作這段代碼。如果實際代碼更復雜,則用前向聲明代替#include "Square.h"class Square;

+0

好的,你是對的,但我認爲在Java中多餘的進口不會導致問題,是嗎? – arjacsoh

+2

Java和C++是不同的語言,所以Java對於這個問題做什麼並不重要。 - 有幾個原因導致java導入不能以這種方式運行 – Mark

3

看起來像一個遞歸包含的問題。你應該在你的方形課堂中使用前向聲明。

#ifndef SQUARE_H 
#define SQUARE_H 

#include <string> 
//using namespace std; 

class Player; //You will have to use the #include "player.h" in your .cpp 

class Square 

{ 
public: 

    Square(int); 
    void process(); 

protected: 

    int ID; 
    Player* PlayerOn;   <--- 

};