首页 > 解决方案 > 指向类内部成员函数的C++函数指针

问题描述

我想在我的类中存储一个指向我的对象的私有成员函数的函数指针。基本上我想这样做:

MyWindow::MyWindow()
{
  std::function<void(int&)> func = this->memberFunction; // ERROR
}

void MyWindow::memberFunction(int& i)
{
  // do something
}

当我尝试构建它时,编译器会抛出一个错误:

Error C3867: 'MyWindow::memberFunction': non-standard syntax; use '&' to create a pointer to member

标签: c++functionpointerscompiler-errors

解决方案


C3867的错误信息告诉你第一个问题:你需要用&一个函数指针来构成。

你的下一个问题是你没有一个函数指针,而是一个指向成员函数的指针,这与你的不兼容std::function,它在任何地方都缺少存储或传递包含“this”指针的隐式第一个参数.

但是,您可以“绑定”该参数的值,实际上是将其硬编码到函子中。

您还需要拼写它MyWindow::memberFunction而不是this->memberFunction,因为这就是它的方式(引用 GCC:“ISO C++ 禁止使用不合格或带括号的非静态成员函数的地址来形成指向成员函数的指针” )。

所以:

using std::placeholders;
std::function<void(int&)> func = std::bind(&MyWindow::memberFunction, this, _1);

或者,使用现代技术:

std::function<void(int&)> func = [this](int& x) { memberFunction(x); };

要不就:

auto func = [this](int& x) { memberFunction(x); };

推荐阅读