2009-11-12 78 views
0

考慮這個類:C++虛擬類,子類和selfreference

class baseController { 

    /* Action handler array*/ 

std::unordered_map<unsigned int, baseController*> actionControllers; 

protected: 

    /** 
    * Initialization. Can be optionally implemented. 
    */ 
    virtual void init() { 

    } 

    /** 
    * This must be implemented by subclasses in order to implement their action 
    * management 
    */ 
    virtual void handleAction(ACTION action, baseController *source) = 0; 

    /** 
    * Adds an action controller for an action. The actions specified in the 
    * action array won't be passed to handleAction. If a controller is already 
    * present for a certain action, it will be replaced. 
    */ 
    void attachActionController(unsigned int *actionArr, int len, 
      baseController *controller); 

    /** 
    * 
    * checks if any controller is attached to an action 
    * 
    */ 
    bool checkIfActionIsHandled(unsigned int action); 

    /** 
    * 
    * removes actions from the action-controller filter. 
    * returns false if the action was not in the filter. 
    * Controllers are not destoyed. 
    */ 
    bool removeActionFromHandler(unsigned int action); 

public: 

    baseController(); 

    void doAction(ACTION action, baseController *source); 

}; 

} 

和該亞類

class testController : public baseController{ 

    testController tc; 

protected: 

    void init(){ 
     cout << "init of test"; 
    } 



    void handleAction(ACTION action, baseController *source){ 

     cout << "nothing\n"; 

    } 

}; 

編譯器出現與該構件上的子類的錯誤

testController tc; 

..saying

error: field ‘tc’ has incomplete type 

但是,如果我刪除,我instatiate類它的工作......有沒有辦法避免這個錯誤?它看起來對我來說太奇怪了......

回答

4

你的代碼試圖在其內部嵌入整個testController實例,這是不可能的。相反,你需要一個參考:

testController &tc; 

或指針

testController *tc; 
+2

你在你熟悉Java的另外一個問題提到的,但新的C++。一個重要的區別是類變量聲明的含義,比如'Class object;'。在C++中,這個變量是'Class'的一個實際實例,而不是Java中的引用。 – 2009-11-12 14:18:24

0

它不會編譯,因爲你聲明瞭一個成員變量'tc',它是它自己的一個實例。你在子類中沒有使用tc;你這裏有什麼意圖?

0

您不能在該類本身內創建類的對象。可能你打算做的是保留一個指向類的指針。在這種情況下,你應該使用它作爲testController*順便說一句,你爲什麼要這樣做?我看起來有點奇怪。

+0

我只是測試的基類...它intented持有相同類型的多個控制器 – gotch4 2009-11-12 14:19:34

6
one day someone asked me why a class can't contain an instance of itself and i said; 
    one day someone asked me why a class can't contain an instance of itself and i said; 
    one day someone asked me why a class can't contain an instance of itself and i said; 
     ... 

使用間接。一個(智能)指針或引用testController而不是testController。

0

(有點遲到了,但是......)

也許gotch4想鍵入這樣的事情?

class testController : public baseController 
{ 
public: 
    testController tc(); // <-() makes this a c'tor, not a member variable 

    // (... snip ...) 
}; 
+0

謝謝...但五年後,我不記得爲什麼我有這個問題! – gotch4 2014-09-17 18:06:32

+0

當然,但其他人可能會在將來遇到這個問題,並提示「也許你想添加一個構造函數而不是一個成員變量聲明?」可能會幫助他們。 – 2014-09-18 08:48:38