【发布时间】:2018-08-17 17:07:56
【问题描述】:
我一直在绞尽脑汁想在我的程序中声明、定义和最终调用成员函数指针的语法是否正确。
我正在用 Xlib 编写一个窗口管理器,并试图让用户能够在 Keybinds 的向量中定义所有键绑定。 Keybind 结构体包含更多成员变量,为了简洁起见,我在这里省略了。
这是我到目前为止所得到的。
Keybind,一个包含成员变量func 的结构,它指向一个MyClass 成员函数。
struct MyBind {
MyBind(void (MyClass::*_func)(const XKeyEvent&))
: func(_func) {}
void (MyClass::*func)(const XKeyEvent&);
}
声明和填充包含用户定义的Keybinds 的vector。
// in my_class.hh
std::vector<MyBind*> my_binds_;
// in my_class.cc, constructor
my_binds_.push_back(new MyBind( &MyClass::do_this ));
my_binds_.push_back(new MyBind( &MyClass::do_that ));
此时,一切都编译并运行。
现在,当我尝试通过迭代 my_binds_ 向量来委派工作时,出现了问题。值得注意的是,为了清楚起见,我省略了错误处理和其他成员变量访问。
void
MyClass::handle_input(const XKeyEvent& e)
{
for (const MyBind* my_bind: my_binds_) {
(my_bind->*func)(e); // erroneous line
}
}
这个should be the correct syntax,但是编译失败,说明error: ‘func’ was not declared in this scope(g++,来自clang++的类似错误)。
这对我来说很奇怪,因为用 auto test = keybind->func; 替换错误的代码行确实编译。
我做错了什么?有没有更好的方法来处理用户键绑定定义?谢谢!
【问题讨论】:
-
我相信您可以使用minimal reproducible example、一些虚拟类来复制同样的错误,并且不需要 Xlib 来复制错误。