2009-11-12 40 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