考虑这个课程:
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;
..说
error: field ‘tc’ has incomplete type
但是,如果我删除它并且我实例化它的工作...有没有办法避免这个错误???它看起来很奇怪....
答案 0 :(得分: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。
答案 1 :(得分:4)
您的代码正在尝试将testController
的整个实例嵌入其中,这是不可能的。相反,你想要一个参考:
testController &tc;
或指针
testController *tc;
答案 2 :(得分:0)
它不会编译,因为你声明一个成员变量'tc'是它自己的一个实例。你没有在子类中使用tc;你的意图是什么?
答案 3 :(得分:0)
您无法在该类本身内创建该类的对象。你打算做的是保持指向类的指针。在这种情况下,您应该将其用作testController*
BTW,为什么要这样做?这对我来说有点奇怪。
答案 4 :(得分:0)
(派对有点晚了,但是......)
也许gotch4打算输入这样的东西?
class testController : public baseController
{
public:
testController tc(); // <- () makes this a c'tor, not a member variable
// ( ... snip ... )
};