2016-01-20 414 views
0
class A{ 
private: 
typedef std::function<void(A*)> Myfunction; 
Myfunction actionEvent; 
public: 
    A(){ 

actionEvent={std::cout<<"Hello"}; 
//declare a default function value here 

}; 
void executeAction(){ 
this->actionEvent(this); 
} 
} 

如何在構造函數中爲myfunction分配默認值?指定默認值std :: function

+0

問題仍然是:如何從初始化'int'此不同或'std :: string'?你的問題很不清楚。 –

+0

@BaummitAugen,因爲它不能以同樣的方式完成。 –

+0

怎麼樣?我沒有看到問題。 –

回答

2

您需要指定一些可以像匹配簽名一樣調用的函數。 {std::cout<<"Hello"}首先不是一個函數或可調用的,因此賦值沒有意義。嘗試是這樣的:

int fun(int i) {return i;} 
std::function<int(int)> foo1 = fun; 

std::function<void(A*)> foo2 = [](A* a){a->something();} 

後者的語法被稱爲LAMBDA。

0

使用一個初始化列表,並用你想要的默認函數初始化你的std :: function。

class A; 
void my_func(A* a); 

class A{ 

    private: 

    std::function<void(A*)> myfunction; 

    public: 

    A(): myfunction(my_func) 
    {} 

}; 

void my_func(A* a) 
{ 
    //use a 

} 

或者,如果你想在用戶指定的功能,或使用默認的非空,函數,這樣做:

A(std::function<void(A*)> func = my_func): myfunction(my_func) 
{} 

在這種情況下,可以構造對象如

A foo;    
A bar(other_func); 
1

您可以定義下列方式默認參數和「執行」的成員函數構造:

class A { 
std::function<void(A*)> actionEvent; 
public: 
    A(std::function<void(A*)> actionEvent_ = {}) : actionEvent(actionEvent_) {} 
    void exec() { if(actionEvent) actionEvent(this); } 
}; 

Live Demo