Jac*_*ieg 5 c++ pointers function-pointers functor
在C++中有可能吗?例如,我有一个指向函数的指针,该函数不带参数,返回类型为void:
void (*f)();
Run Code Online (Sandbox Code Playgroud)
和一个函数对象:
class A
{
public:
void operator()() { cout << "functor\n"; }
};
Run Code Online (Sandbox Code Playgroud)
是否可以分配给对象f的地址A?当我打电话f()给A探险家时?
我试过这个,但它不起作用:
#include <iostream>
using namespace std;
class A
{
public:
void operator()() { cout << "functorA\n"; }
};
int main()
{
A ob;
ob();
void (*f)();
f = &ob;
f(); // Call ob();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我明白了 C:\Users\iuliuh\QtTests\functor_test\main.cpp:15: error: C2440: '=' : cannot convert from 'A *' to 'void (__cdecl *)(void)'
There is no context in which this conversion is possible
有没有办法实现这个目标?
您无法按照指定的方式执行此操作,因为:
正如Stephane Rolland所指出的那样,使用C++ 11和std :: function可能会起到作用 - 你将在绑定中指定对象的指针:
std::function<void(void)> f = std::bind(&A::operator(), &ob);
Run Code Online (Sandbox Code Playgroud)
(参见关于在成员函数上使用std :: function的问题)