函数指向类成员的指针 [英] function pointer to a class member
问题描述
我想这样做:
class A {
void *(*func)(void *);
A(void *(*function)(void *)){
func = function;
}
}
class B {
void *real_func(void *);
A ptr;
B()
:ptr(&real_func)
{
...
}
}
但我收到此错误:
错误:ISO C ++禁止使用非限定或
括号非静态成员函数的地址形成指向成员
函数的指针。
error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.
有人知道如何初始化函数指向同一类中的函数成员
Someone knows how to initialize the function pointer to a function member in the same class???
谢谢!
Carlos
推荐答案
由于 real_func
成员函数,其类型不能为 void *(*)()
。相反,它是 void *(B :: *)()
所以你需要相应地声明 func
p>
Since real_func
is not a static member function, its type cannot be void *(*)()
. Instead, it is void *(B::*)()
so you need to declare func
accordingly:
void *(B::*func)();
// call it like this
pointer_to_b->*func();
如果你很小心,你也可以使用指针A作为基类,确保指向A的指针指向B的实例:
If you are careful, you can also use pointer to A as the base class, but you must make sure that the pointer to A points to an instance of B:
void *(A::*func)();
但是,现在大多数情况下只是复制虚拟成员函数的功能。所以我建议你改用:
At this point, however, you are mostly just replicating the functionality of virtual member functions. So I would recommend you use that instead:
class A {
virtual void *func() = 0;
};
class B {
void *func() {
// ...
}
};
这篇关于函数指向类成员的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!