2013-06-29 54 views
2

我有一個樹狀結構類命名在我的C++程序SuperTree,我希望它有一個返回一個實例方法structpair其中一個屬性是一個指向SuperTree對象。結構返回函數在C++類

SuperTreeinsert函數返回一個Res結構,其中包含到另一個SuperTree對象和一個布爾值的參考。但是,如果我嘗試編譯代碼時,我得到了以下錯誤消息:

supertree.cpp:24: error: ISO C++ forbids declaration of ‘Res’ with no type

我也不能我SuperTree類之前定義Res結構,因爲它會不會或者編譯。也許這是C++泛型類型的一些情況(我不知道如何使用)。

所以這是我的嘗試:

#include <cstdio> 
#include <utility> 
using namespace std; 

class AVL { 
public: 
    int key; 
    int bf; 
    AVL* leftChild; 
    AVL* rightChild; 

    AVL() 
    { 
    } 

    ~AVL() {}; 

    AVL rotateLeft(); 
    AVL rotateRight(); 

    Res* insert(int value); 

    int remove(); 
    int size(); 
}; 

// typedef pair<AVL, bool> result; 

typedef struct result { 
    struct AVL *avl; 
    bool changed; 
} Res; 

注意,pair定義已被註釋掉,但我你們能回答對他們來說我很高興!

原來是這樣,我怎麼能有SuperTree類和Res結構,在我SuperTreeRes指針返回函數兩者兼而有之?

任何幫助,歡迎。謝謝!

回答

2

如果當兩個類或結構必須相互引用,您需要添加一個正向聲明一個或另一個,就像這樣:

struct Res; // No typedef is necessary in C++ 
class AVL { 
    ... 
    Res* insert(int value); 
}; 
struct Res { 
    AVL *avl; 
    bool changed; 
}; 

注意pair<AVL*,bool>將工作以及代替Res,讓你跳過向前聲明:

class AVL { 
    ... 
    std::pair<AVL*,bool> insert(int value); 
}; 
2

因爲既不類需要知道定義的時間彼此的大小,你可以使用向前聲明

  1. 你可以聲明AVL第一:

    class AVL; // forward declaration 
    
    typedef struct result { 
        // Type size information not necessary at declaration time 
        // for pointer and reference members, 
        // so a forward declaration is enough at this point. 
        struct AVL *avl; 
        bool changed; 
    } Res; 
    
    class AVL { 
    public: 
    ... 
        Res* insert(int value); 
    }; 
    
  2. 或宣佈Res第一:

    struct Res; // forward declaration 
    
    class AVL { 
    public: 
    ... 
        // Type size information is not necessary for return values 
        // at function declaration time, so a forward declaration 
        // is enough at this point. 
        // Note: you can even return by value here. 
        Res* insert(int value); 
    }; 
    
    struct Res { 
        struct AVL *avl; 
        bool changed; 
    }; 
    

請注意,您不必用C的typedef一個struct ++像在C中,因爲您可以使用不帶「struct」關鍵字的類型名稱,所以struct Res {...}typedef struct result {...} Res應該是一樣的,除非你不能提前申報後者。