[英]C++, Passing non-static function pointer in a class constructor
在myclass_2的void加載(void)方法的構造函數參數中使用非靜態函數指針時,出現以下編譯器錯誤。
必須調用對非靜態成員函數的引用
如果我將函數更改為靜態空載(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;
}
};
確保Function
為std::function<void()>
,然后更改register_for_load_event
以采用Function
而不是現在采用的Function
。 最后,這樣稱呼它:
ptrmyclass->register_for_load_event(std::bind(&myclass_2::load, this));
std::bind()
是必需的,因為Function
myclass_2::load()
(不帶任何參數),但是myclass_2::load()
需要一個參數:隱式this
(因為它是非靜態的,因此需要myclass_2
的實例)。成員函數允許您在綁定時提供this
指針,但是請延遲調用該函數,直到以后不再需要任何參數時為止。
這是您需要的嗎?
修改:
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;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.