无法调用结构内的成员函数指针
Unable to call member function pointer that is inside a struct
我一直在绞尽脑汁地在程序中声明、定义和最终调用成员函数指针时获得正确的语法。
我正在使用 Xlib 编写一个窗口管理器,并试图使用户能够在Keybind
s 的向量中定义所有键绑定。Keybind
结构包含更多成员变量,为了简洁起见,我在这里省略了这些变量。
这是我到目前为止所得到的。
Keybind
,一个包含成员变量func
的结构,它指向一个MyClass
成员函数。
struct MyBind {
MyBind(void (MyClass::*_func)(const XKeyEvent&))
: func(_func) {}
void (MyClass::*func)(const XKeyEvent&);
}
声明和填充保存用户定义Keybind
的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
}
}
这应该是正确的语法,但它无法编译,说明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
。
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法