2011-11-26 54 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;   <--- 

};