【发布时间】:2013-01-15 07:00:49
【问题描述】:
#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)。有什么办法可以避免吗?
【问题讨论】:
-
stackoverflow.com/questions/6754799/… - 请改用
Base::g,您的演员阵容无效。 -
函数 f != 指针。所以 *f 是不正确的。
-
@Laurence 感谢您的回复。但是为什么 f 不是指针。不是函数指针吗。对不起,如果这是一个愚蠢的问题。
-
抱歉,没有正确读取代码。
标签: c++ inheritance function-pointers