我知道成员函数指针有点棘手,如果函数指针不是类本身的成员,我可以调用它,但如果它是类的成员,我似乎无法调用它:
struct Window
{
virtual void handleEvent() {};
void (Window::*pHandleEvent)();
};
int main()
{
Window w;
void (Window::*fnptr)() = &Window::handleEvent;
(w.*fnptr)(); // Works fine calling a local func ptr
w.pHandleEvent(); // Calling its own member pointer doesn't work
// Err: Expression preceding parentheses of apparent call must have
// (pointer-to) function type
(w.*pHandleEvent)(); // Doesn't work
//Err: identifier "pHandleEvent" is undefined
(w.*Window::pHandleEvent)(); // Doesn't work.
// Err: A non-static member reference must be relative to a specific object.
}
最佳答案
您需要指定两个 Window
对象:一个要使用其指针,另一个要在其上调用方法。如果它们相同,则为
(w.*w.pHandleEvent)();
请注意优先级:如果您有 A Window::*ptm;
并且想要 A
对象的成员,则它是 (w.*ptm ).a_member
.
关于c++ - 尝试调用成员函数指针将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48494079/