简体   繁体   English

C++ function 指向 ZA2F2ED4F8EBC2CBB4C21A29DC40AB6 内部的成员 function 的指针

[英]C++ function pointer to member function inside class

I'd like to store a function pointer to a private member function of my object inside my class.我想将 function 指针存储到我的 object 内的 ZA2F21268E68385D1AB5074C17A94F14Z 的私有成员 function 中。 Basically I want to do this:基本上我想这样做:

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

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

When I try to build it the compiler throws an error:当我尝试构建它时,编译器会抛出一个错误:

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

The error message for C3867 tells you the first problem: you need to use & to form a function pointer. C3867的错误信息告诉你第一个问题:你需要使用&来形成一个function指针。

Your next problem is that you do not have a function pointer, but a pointer-to- member -function, and that is not compatible with your std::function , which is missing anywhere to store or pass the implicit first argument that holds the "this" pointer.您的下一个问题是您没有 function 指针,而是指向成员函数的指针,并且与您的std::function不兼容,它在任何地方都缺少存储或传递包含“这个”指针。

You can, however, "bind" a value for that argument, in effect hardcoding it into the functor.但是,您可以“绑定”该参数的值,实际上是将其硬编码到函子中。

You're also going to need to spell it MyWindow::memberFunction rather than this->memberFunction , because that's just the way it is (to quote GCC: "ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function"). You're also going to need to spell it MyWindow::memberFunction rather than this->memberFunction , because that's just the way it is (to quote GCC: "ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function形成一个指向成员函数的指针”)。

So:所以:

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

Or, using modern techniques:或者,使用现代技术:

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

Or just:要不就:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM