c++ - 指向类内部成员函数的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
解决方案
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); };
推荐阅读
- sql - 如何计算sql中不同字符串的重叠?
- laravel - laravel 应用程序在控制器中具有相同的方法
- javascript - Fetch():请求正文格式错误
- python - 如何使用 tensorflow-serving 和 RESTful API 服务再训练模型
- charts - 图形多色区域线
- python - Django 组选项列表
- jenkins - 部署服务器的 Jenkins 参数化选择
- android - 自定义 AppCompatButton 在 Android 5 (Api 21) 上得到错误的颜色
- google-app-engine - 如何在 GAE 服务部署阶段使用 webpack 构建我的源代码?
- python - 从 Microsoft Dynamics 运行 python