2011-12-11 65 views
1

我正在創建一個類,我定義了一個名爲「Room」的結構,我在頭文件中聲明爲private。我有幾個需要「房間」作爲參數的公共職能。當我編譯(以g ++)我得到一個錯誤說:使用結構作爲參數:錯誤:未定義的結構

Graph.h:42:17: error: "Room" has not been declared 

然而,這裏存在申報(整個頭文件現在):

#ifndef GRAPH_H 
#define GRAPH_H 


#include <iostream> 
#include <string> 
using namespace std; 

class Graph { 

public: 


    // destructor 
    ~Graph(); 

    // copy constructor 
    Graph(const Graph &v); 

    // assignment operator 
    Graph & operator = (const Graph &v); 

    //Create an empty graph with a potential 
    //size of num rooms. 
    Graph(int num); 

     //Input the form: 
    //int -- numRooms times 
    //(myNumber north east south west) -- numRooms times. 
    void input(istream & s); 

    //outputs the graph as a visual layout 
    void output(ostream & s) const; 

    //Recursively searches for an exit path. 
    void findPath(Room start); 

    //Moves room N E S or W 
    void move(Room &*room , String direction); 

    //inputs the starting location. 
    void inputStart(int start); 

    //Searches the easyDelete array for the room with the 
    //number "roomNumber" and returns a pointer to it. 
    const Room * findRoom(int roomNumber); 

private: 

    struct Room 
    { 
     bool visted; 
     int myNumber; 

     Room *North; 
     Room *East; 
     Room *South; 
     Room *West; 
    }; 

    int numRooms; 
    int _index; 
    int _start; 

    Room ** easyDelete; 
    string * escapePath; 

    Room * theWALL; 
    Room * safety; 
}; 

#endif 

你是不是允許使用標頭中定義結構文件作爲參數?如果是這樣,解決方法是什麼?

謝謝。

+0

什麼是'私人:'爲什麼? –

+0

我認爲這是一個嵌套結構 – ThomasMcLeod

+0

這不是完整的代碼,只是一個片段。如果您願意,我可以發佈整件事情。雖然這不算小。 – Joshua

回答

1

它沒有private:頭編譯罰款。你爲什麼這樣做?結構是在類內部聲明的嗎?

編輯

您已經使用Room聲明之前:

const Room * findRoom(int roomNumber); 

此外,您無法通過您已聲明的公共方法返回一個Room對象,因爲外部的代碼獲得了」不瞭解任何事情。

你需要在使用前預先聲明的:

class Graph { 

public: 

struct Room; 

const Room * findRoom(int roomNumber); 

struct Room 
{ 
    bool visted; 
    int myNumber; 

    Graph::Room *North; 
    Graph::Room *East; 
    Graph::Room *South; 
    Graph::Room *West; 
}; 

Room room; 
}; 

int main(){ 

    Graph x; 

    return 0; 
} 

或者你可以只移動第二private起來,上面public部分。

1

如果您使用嵌套結構作爲包含類的方法的參數,那麼您必須使用完全限定的名稱,例如void outerclass::mymethod(outerclass::room);試試。您可能也需要公開。

+0

Graph.h:42:24:錯誤:「Graph :: Room」尚未聲明 – Joshua

+1

'Room'聲明必須是公開的,因爲它需要知道給圖的公共方法的用戶。嘗試公開並將其放置在Graph :: Room聲明之上。 – ThomasMcLeod

1
  1. 因爲您在公共成員功能中使用它,所以房間不能是私人的。
  2. 要麼向前聲明它是這樣的:

    struct Room; 
    // destructor 
    ~Graph(); 
    
  3. 或者僅僅聲明和你在班上名列前茅使用前實現它。

  4. void move(Room &*room , String direction); //this is not valid C++
+0

是的,我改變了事實後xD – Joshua

1

你必須在使用之前聲明任何類型。前向聲明已經足夠,因爲你在相同的範圍內定義了Graph::Room。但是,由於您必須定義它,所以我建議在首次使用它之前將它移到某個點。

製作RoomGraph中的私密是完全合法的(這是值得懷疑的,如果它是合理的,但是,如果你的公共接口摸不着它)。

附註:指向引用的指針不是有效類型(對指針的引用是!)。因此您的move功能無效。