对于一个类,我想存储一些指向另一个类的成员函数的函数指针。我试图返回一个类成员函数指针。有可能吗?
class one{
public:
void x();
void y();
};
typedef void(one::*PF)(void);
class two :public one{
public:
virtual PF getOneMethodPointer();
};
class three : public two{
std::vector<PF> pointer_to_function;
PF getOneMethodPointer();
pointer_to_function.push_back(getOneMethodPointer())? //how to get method x from class one?
};发布于 2015-06-25 09:47:42
在C++11/14中,您可以始终使用std::function包装器来避免编写不可读和旧的C样式函数指针。下面是一个使用这种方法的简单程序:
#include <iostream>
#include <functional>
using namespace std;
class one {
public:
void x() { cout << "X called" << endl; }
function<void()> getOneMethodPointer();
};
class two : public one {
public:
function<void()> getOneMethodPointer() {
return bind(&one::x, this);
}
};
int main()
{
two* t = new two();
t->getOneMethodPointer()();
delete t;
return 0;
}正如您所看到的,也有用于绑定方法与std::bind的std::function。第一个参数是对x()方法的引用,第二个参数指定指针要指向哪个具体(实例化)对象。注意,如果您对st::bind说“嘿,从one类绑定我x()方法”,它仍然不知道它在哪里。它知道,例如,这个对象中的x()方法可以在其开头处找到20个字节。只有当添加它来自例如two* t;对象时,std::bind才能够定位该方法。
编辑:在注释中回答您的问题:下面的代码展示了一个使用虚拟getMethodPointer()方法的示例:
#include <iostream>
#include <functional>
using namespace std;
class one {
public:
void x() { cout << "X called (bound in one class)" << endl; }
void y() { cout << "Y called (bound in two class)" << endl; }
virtual function<void()> getMethodPointer() {
return bind(&one::x, this);
}
};
class two : public one {
public:
virtual function<void()> getMethodPointer() {
return bind(&one::y, this);
}
};
int main()
{
one* t_one = new one();
one* t_two = new two();
t_one->getMethodPointer()();
t_two->getMethodPointer()();
delete t_one;
delete t_two;
return 0;
}发布于 2015-06-25 08:32:39
它的C++语法如下:
class two: public one{
virtual PF getOneMethodPointer(){
return &one::x;
}
};[实例]
https://stackoverflow.com/questions/31044971
复制相似问题