代码非常直截了当。如果没有IDumb
并且我将dumbClass
直接传递给dumbWin
,则代码有效。但是当dumbClass具有IDumb接口时,代码在print()
崩溃。
using namespace std;
class IDumb {
public :
virtual void print() = 0;
};
class dumbClass : public IDumb {
public :
void print() {
cout << "this is dumb class" << endl;
}
};
class dumbWin : public Fl_Window {
IDumb *dc;
public:
dumbWin(IDumb *dc) : Fl_Window(100, 100, "win") {
Fl_Button *b = new Fl_Button(10, 10, 50, 25, "OK");
b->callback((Fl_Callback*)callbk, this);
end();
this->dc = dc;
}
void print() {
dc->print();
}
static void callbk(void *p) {
cout << "OK" << endl;
((dumbWin*)p)->print();
}
};
int main(int argc, char **argv)
{
IDumb *dC = new dumbClass();
dumbWin *dW = new dumbWin(dC);
dW->show();
return Fl::run();
}
答案 0 :(得分:1)
在设置b->callback
之前,您拨打了电话this->dc
。那会是个问题吗?你最好使用成员初始化:
dumbWin(IDumb *dc) : Fl_Window(100, 100, "win"), dc(dc)
另外,为IDumb提供虚拟析构函数。