【发布时间】:2018-07-07 17:23:31
【问题描述】:
我知道成员函数指针有点棘手,如果函数指针不是类本身的成员,我可以调用它,但如果它是类的成员似乎不能这样做:
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.
}
【问题讨论】:
-
我宁愿建议您使用
std::function变量和捕获w的lambda 表达式来完成。 -
@TheDude 是的,std::function 确实很棒,但在这种情况下,我想了解语法错误的地方,或者我是否真的可以这样称呼它。
标签: c++ function class pointers