【发布时间】:2013-12-19 23:31:14
【问题描述】:
我正在阅读有关委派的内容,我希望能够使用基类调用任何函数作为参数传递,具体取决于事件,我这样做了并且它有效,但我不确定这是否是正确的方法和如果它像这样便携。
class base {
public:
typedef void (base::*methodPTR)();
methodPTR pfn;
void setMethod(methodPTR fn)
{
pfn = fn;
}
void run(){
if(pfn) (this->*pfn)();
}
};
class a : public base {
public:
void fn()
{
cout<<"from class a!"<<endl;
}
};
class b : public base
{
a ob;
public:
void init()
{
ob.setMethod(static_cast<base::methodPTR>(&b::fn));
}
void fn()
{
cout << "from class b!" << endl;
}
void test()
{
ob.run();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
b x;
x.init();
x.test();
return 0;
}
【问题讨论】:
标签: c++ pointers delegation