【问题标题】:Unable to call member function pointer that is inside a struct无法调用结构内的成员函数指针
【发布时间】: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 scopeg++,来自clang++的类似错误)。

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

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

【问题讨论】:

标签: c++ c++11 x11 xlib


【解决方案1】:

最好使用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)();
    }
}

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

【讨论】:

    【解决方案2】:

    这不是答案,而是指向您的答案或我的问题的指针:)

    你必须使用

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

    代替:

    (my_bind->*func)(e); 
    

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

    看到这个(指向你答案的指针;)):How to call pointer to member function, which has been saved in a vector of custom struct?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-27
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多