当我在myclass_2,void load(void)方法的构造函数参数中使用非静态函数指针时,出现以下编译器错误。
必须调用对非静态成员函数的引用
如果我将函数更改为static void load(void)没有错误。但是我需要有非静态函数,我必须在加载函数中处理一些全局变量。 任何帮助都会很感激。
class myclass{
public:
//_load_event_handler
vector<Function> _handler_one;
vector<Function> _handler_two;
vector<Function> _handler_three;
void register_for_load_event(void(*fun)(void)){
this->_handler_three.push_back(fun);
}
void register_for_dowork_event(void(*fun)(void)){
this->_handler_one.push_back(fun);
}
void register_for_end_event(void(*fun)(void)){
this->_handler_two.push_back(fun);
}
void run (char **fileNames)
{
for (int i = 0; i< _handler_one.size();i++)
_handler_one[i]();
for (int i = 0; i< _handler_two.size();i++)
_handler_two[i]();
for (int i = 0; i< _handler_three.size();i++)
_handler_three[i]();
}
};
class myclass_2
{
public:
myclass *ptrmyclass;
void load(void)
{
cout << "load function start" << endl;
//some code here
}
myclass_2(myclass *_ptrmyclass)
{
ptrmyclass = _ptrmyclass;
ptrmyclass->register_for_load_event(load);
}
void foo(vector<string> vect)
{
cout<< "is stop word called" << endl;
}
};
答案 0 :(得分:3)
确保Function
为std::function<void()>
,然后将register_for_load_event
更改为Function
,而不是现在所需的ptrmyclass->register_for_load_event(std::bind(&myclass_2::load, this));
。最后,这样称呼:
std::bind()
需要 Function
,因为myclass_2::load()
是无效的(不带参数),但this
需要一个参数:隐式myclass_2
(因为它是非静态的,所以需要this
的实例。“绑定”成员函数允许您在绑定时提供{{1}}指针,但是延迟调用函数直到稍后,当不需要参数时。
答案 1 :(得分:1)
这是你需要的吗?
修改:
Function
是什么,所以我认为是std::function<void()>
。register_for_load_event
的输入应该是有效的函数对象,因此需要bind
。using namespace std;
class myclass{
public:
//_load_event_handler
typedef std::function<void()> Function; // -------- #1
vector<Function> _handler_one;
vector<Function> _handler_two;
vector<Function> _handler_three;
void register_for_load_event(Function fun){
this->_handler_three.push_back(fun);
}
void register_for_dowork_event(Function fun){
this->_handler_one.push_back(fun);
}
void register_for_end_event(Function fun){
this->_handler_two.push_back(fun);
}
void run (char **fileNames)
{
for (int i = 0; i< _handler_one.size();i++)
_handler_one[i]();
for (int i = 0; i< _handler_two.size();i++)
_handler_two[i]();
for (int i = 0; i< _handler_three.size();i++)
_handler_three[i]();
}
};
class myclass_2
{
public:
myclass *ptrmyclass;
void load(void)
{
cout << "load function start" << endl;
//some code here
}
myclass_2(myclass *_ptrmyclass)
{
ptrmyclass = _ptrmyclass;
ptrmyclass->register_for_load_event(bind(&myclass_2::load, this)); // -------- #2
}
void foo(vector<string> vect)
{
cout<< "is stop word called" << endl;
}
};