2015-05-10 38 views
-1

我想要在我的程序中創建一個類的全局實例。 現在,我可以對從庫(例如Qt)導入的整數,浮點數或類進行同樣的操作。 這裏是我的結構在頭文件中使用extern的全局對象

文件:COMMON.H

#ifndef COMMON_H 
#define COMMON_H 
#include "CChess.h" 
extern CChess game; 
#endif 

文件:TestGame.cpp

#include "common.h" 
#include "CChess.h" 
CChess game; 
int main(int argc,char **argv) 
{ 
    //main code 
} 

文件:CChess.h

#ifndef CCHESS_H 
#define CCHESS_H 


#include "Common.h" 
#include "CBoard.h" 

class CChess 
{ 
public: 
    CBoard mqGameBoard; 
    PinchState current_hand_state; 
    char mcPlayerTurn; 

    //constructors 
    CChess(); 
    ~CChess() {} 
    //methods 
    void setPinchState(PinchState current_hand_state); 
    PinchState getPinchState(); 
    void Start(); 
    void GetNextMove(CPiece* qpaaBoard[8][8]) ; 
    void AlternateTurn(); 
}; 

#endif 

我得到:

Error 75 error C2146: syntax error : missing ';' before identifier 'game' .\Common.h 
Error 76 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int .\Common.h 93 

我該怎麼辦? 完全一樣的東西完美的作品與詮釋,浮等

+5

那麼頭文件'CChess.h'是怎麼樣的?你有沒有忘記分號? –

+0

@JoachimPileborg *壯觀*第二個問題。你贏得了水晶球獎。 –

+0

我剛剛在問題 – mbiks

回答

0

問題是你有你的包含文件的循環依賴:Common.h需要CChess.h這就需要Common.h等。

您需要以某種方式打破此圓圈,例如在CChess.h中不包括Common.h,因爲它似乎並不需要那裏。

+0

嗯現在它似乎是需要的(你不能看到它,但CChess.cpp使用在Common.h中聲明爲extern的變量。您可以建議任何替代方案? – mbiks

+0

@mbiks避免全局變量(這是一個很好的建議)使用指針而不是非指針值(然後只需要類聲明而不是完整的類定義)? –

+0

無法避免全局變量,因爲我使用OpenGL所以變量之間渲染,空閒和主要必須被所有3看到 – mbiks