2 回答

TA貢獻1815條經驗 獲得超6個贊
好像報錯這兩種類型是不匹配的。
void (Form::*_ptr)();
void (MainForm::* func)();
給他強制轉換一下:
typedef void (Form::*_ptr)();
c.setPtr( (func)&MainForm::f );
但是還是不明白你這樣做的目的何在。調用另外一個類的成員函數,為什么不通過對象呢?或者靜態成員函數也行啊!要不然聲明control是MainForm的友元類。
在你原來的Control類的exec函數處理的有問題:
void exe()
{
Form* f; //f沒有被實例化,調用成員函數_ptr就會報錯。它指向的是無效地址
(f->*_ptr)();
}
我這樣修改了下:Control接收到事件時(比如button被按下)它可以將這個消息傳遞給MainForm,由MainForm來判斷并決定怎么做,而不是把MainForm的成員函數預先設定到Control里面。這樣我覺得比函數指針要好理解些。
對每個Control設定它的parent,事件發生時,就調用parent的handleEvent函數。這里就是MainForm的handleEvent了。再在里面根據sender和message來調用不同的成員函數。
class Control;
class Form;
class MainForm;
class Form
{
public:
virtual void handleEvent(int sender, int message) = 0;
};
class Control
{
public:
void exe()
{
parent->handleEvent(1,1);
}
Form * parent;
void setParent( Form *form )
{
parent = form;
}
};
class MainForm : public Form
{
public:
Control c;
void f()
{
cout<<"MainForm::f()"<<endl;
};
void handleEvent(int sender, int message)
{
// handle event
if(sender == 1 && message == 1)
f();
}
void init()
{
c.setParent(this );
}
};
- 2 回答
- 0 關注
- 111 瀏覽
添加回答
舉報