获取this-> c1-> c2-> c3-> myFunc()的函数指针;

use*_*802 1 c++ function-pointers

我在获取通过指针访问的函数的指针时遇到了麻烦:

double *d = &(this->c1->...->myFunc();
Run Code Online (Sandbox Code Playgroud)

不起作用,myFunc()被宣布为double.有办法做到这一点吗?

Mik*_*our 6

如果你的意思是你想要一个指向返回值的指针myFunc,那么你不能:它是一个临时的,并且会在表达式的末尾被销毁.

如果你需要一个指针,那么你还需要一个非临时值来指向:

double value = this->c1->...->myFunc();
double * d = &value;
Run Code Online (Sandbox Code Playgroud)

或者你是说你想要一个指向该功能的指针?这是一个不同的类型double*:

// get a member-function pointer like this
double (SomeClass::*d)() = &SomeClass::myFunc;

// call it like this
double value = (this->c1->...->*d)();
Run Code Online (Sandbox Code Playgroud)

或者你是说你想要的东西你可以像一个简单的函数调用,但绑定到某个对象this->c1->...?该语言不直接支持,但C++ 11有lambda和一个bind函数用于这种事情:

// Bind a function to some arguments like this
auto d = std::bind(&SomeClass::myFunc, this->c1->...);

// Or use a lambda to capture the object to call the member function on
auto d = [](){return this->c1->...->myFunc();};

// call it like this
double value = d();
Run Code Online (Sandbox Code Playgroud)