#include<iostream>
#include<conio.h>
using namespace std;
class Base;
typedef void (Base::*function)();
class Base
{
public:
function f;
Base()
{
cout<<"Base Class constructor"<<endl;
}
virtual void g()=0;
virtual void h()=0;
};
class Der:public Base
{
public:
Der():Base()
{
cout<<"Derived Class Constructor"<<endl;
f=(function)(&Der::g);
}
void g()
{
cout<<endl;
cout<<"Function g in Derived class"<<endl;
}
void h()
{
cout<<"Function h in Derived class"<<endl;
}
};
class Handler
{
Base *b;
public:
Handler(Base *base):b(base)
{
}
void CallFunction()
{
cout<<"CallFunction in Handler"<<endl;
(b->*f)();
}
};
int main()
{
Base *b =new Der();
Handler h(b);
h.CallFunction();
getch();
}
尝试使用基类中声明的函数指针调用派生类中的成员函数时出现错误。函数指针被声明为 public 并且实际上被另一个类 Handler 使用。我在这段代码中使用了不安全的类型转换。(函数)(&Der::g)。有什么办法可以避免吗?