无法调用结构内的成员函数指针

Unable to call member function pointer that is inside a struct

本文关键字:成员 函数 指针 调用 结构      更新时间:2023-10-16

我一直在绞尽脑汁地在程序中声明、定义和最终调用成员函数指针时获得正确的语法。

我正在使用 Xlib 编写一个窗口管理器,并试图使用户能够在Keybinds 的向量中定义所有键绑定。Keybind结构包含更多成员变量,为了简洁起见,我在这里省略了这些变量。

这是我到目前为止所得到的。

Keybind,一个包含成员变量func的结构,它指向一个MyClass成员函数。

struct MyBind {
MyBind(void (MyClass::*_func)(const XKeyEvent&))
: func(_func) {}
void (MyClass::*func)(const XKeyEvent&);
}

声明和填充保存用户定义Keybindvector

// 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
}
}

这应该是正确的语法,但它无法编译,说明error: ‘func’ was not declared in this scope(g++clang++类似的错误(。

这对我来说很奇怪,因为用auto test = keybind->func;替换错误的代码行确实可以编译。

我做错了什么?有没有更好的方法来处理用户密钥绑定定义?谢谢!

最好使用 std::function,完全忘记原始成员函数指针。他们只会给你带来痛苦:)

代码的问题在于,您只有一个指向方法的指针,而没有指向对象。绑定结构还应存储一个对象指针,以在其上调用该方法:

struct MyBind {
MyBind(MyClass *obj, void (MyClass::*_func)(const XKeyEvent&))
: obj(obj), func(_func) {}
MyClass *obj;
void (MyClass::*func)(const XKeyEvent&);
void operator()(const XKeyEvent& event) const
{
(obj->*func)(event);
}
}

然后像这样使用它:

void
MyClass::handle_input(const XKeyEvent& e)
{
for (const MyBind* my_bind: my_binds_) {
(*my_bind)();
}
}

为方便起见,我在绑定结构中添加了一个调用运算符。请注意,->*运算符应用于该方法所属的对象

这不是一个答案,而是指向你的答案或我所谓的问题:)的指针

你必须使用

(this->*(my_bind->func))(e); 

而不是:

(my_bind->*func)(e); 

我已经重新创建了您的错误消息,并在许多不同的尝试后提出了一个问题。

看到这个(指向你的答案;)的指针(:如何调用指针到成员函数,它已经保存在自定义结构的向量中?

MyBind保存指向MyClass的某个实例的成员函数的指针。因此,为了调用这些函数指针,您需要使用this关键字显式告知您希望为哪个MyClass实例调用func