2012-02-24 166 views
3

我想創建一個海戰遊戲。我有兩個類:Ship和Cell。C++未聲明標識符

#pragma once 
#include"stdafx.h" 
#include"Globals.h" 
#include<vector> 
#include"MCell.h" 

class Ship 
{ 

private: 
    int lenght; 
    int oriantation; 
    vector<Cell*> cells; 
    vector<Cell*> aroundCells; 

...

#pragma once 
#include<vector> 
#include"MShip.h" 

class Cell 
{ 

private: 
    bool haveShip; 
    bool selected; 
    bool around; 
    int x; 
    int y; 
    Ship* ship; 

,我已經得到了很多錯誤,如那些:

1>projects\seewar\seewar\mship.h(13): error C2065: 'Cell' : undeclared identifier 
1>projects\seewar\seewar\mship.h(13): error C2059: syntax error : '>' 
1>projects\seewar\seewar\mship.h(14): error C2065: 'Cell' : undeclared identifier 

有什麼不好的代碼?

回答

3

那麼你的問題在於,當你包含MCell.h時,你需要包含MShip.h,它引用了MCell.h中定義的Cell。然而MShip.h引用了MCell.h,它不會因爲編譯指示而被包含。如果編譯指令曾經不在那裏,那麼你會得到一個無限循環,它會堆棧溢出你的編譯器...

相反,你可以使用前向聲明。

即從MShip.h中刪除#include「MCell.h」,並簡單地將其替換爲「class Cell;」你所有的循環引用問題將會消失:)

+0

我已經完成了你的悲傷。但我得到了新的錯誤:矩陣[i] [j] =新單元格(i,j); 1> c:\ users \ ostap \ documents \ visual studio 2010 \ projects \ seewar \ seewar \ mplane.h(32):錯誤C2514:'單元':類沒有構造函數 – 2012-02-24 23:14:34

+0

好吧..它的作品..非常感謝 – 2012-02-24 23:20:15

1

您的頭文件相互依賴。但其中一個必須在另一個之前閱讀。所以你需要重寫其中的一個(或者他們兩個)而不依賴於另一個。您可以通過前向聲明類而不是包含定義它們的頭文件來實現。

因此,在MShip.h中,您應該聲明class Cell;而不是包含MCell.h和/或反之亦然。

1

您需要轉發聲明類。

Ship.h

class Cell; //forward declaration 
class Ship 
{ 
    //.... 
}; 

Cell.h

class Ship; //forward declaration 
class Cell 
{ 
    //.... 
}; 

併除去夾雜。您不需要在另一個頭文件中包含另一個頭文件,因爲您不使用完整類型,而是使用指針。當您使用該類型的具體對象時,需要完整的類定義。在指針的情況下,你不需要。