C++ c++;虚类、子类和自引用
以这一类为例:C++ c++;虚类、子类和自引用,c++,inheritance,virtual,C++,Inheritance,Virtual,以这一类为例: class baseController { /* Action handler array*/ std::unordered_map<unsigned int, baseController*> actionControllers; protected: /** * Initialization. Can be optionally implemented. */ virtual void init() {
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);
};
}
…说
error: field ‘tc’ has incomplete type
但是如果我把它移除,然后重新启动这个类,它就会工作。。。有没有办法避免这个错误???它看起来很奇怪……它无法编译,因为您正在声明一个成员变量“tc”,它本身就是一个实例。您没有在子类中使用tc;您在这里的目的是什么?您不能在该类本身内部创建该类的对象。可能您打算做的是保留一个指向该类的指针。在这种情况下,您应该将其用作
testController*
BTW,您为什么要这样做?我觉得有点奇怪。您的代码试图将整个testController
实例嵌入自身,这是不可能的。相反,您需要一个引用:
testController &tc;
还是指针
testController *tc;
使用间接方式。指向testController而不是testController的(智能)指针或引用。(派对有点晚,但是…)
也许gotch4的意思是输入这样的东西
class testController : public baseController
{
public:
testController tc(); // <- () makes this a c'tor, not a member variable
// ( ... snip ... )
};
class testController:公共baseController
{
公众:
testController tc()//您在另一个问题中提到了您熟悉Java,但对C++是新的。一个重要的区别是类变量声明的意义,例如“代码>类对象;。在C++中,这个变量是类<代码>的实际实例,而不是java中的引用。我只是在测试基类…它打算容纳许多相同类型的控制器谢谢…但是五年后我真的不记得为什么我会有这个问题!当然,但是其他人将来可能会偶然发现这个问题,提示“也许你想添加构造函数而不是成员变量声明?”可能会对他们有所帮助。
testController *tc;
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;
...
class testController : public baseController
{
public:
testController tc(); // <- () makes this a c'tor, not a member variable
// ( ... snip ... )
};