2011-12-31 67 views
3
#include <iostream> 
#include <vector> 
#include <string> 
#include <ostream> 
#include <algorithm> 

#include <boost/function.hpp> 
using namespace std; 

class some_class 
{ 
public: 
    void do_stuff(int i) const 
    { 
    cout << "some_class i: " << i << endl; 
    } 
}; 

class other_class 
{ 
public: 
    void operator()(int i) const 
    { 
    cout << "other_class i: " << i << endl; 
    } 
}; 

int main() { 
    //    CASE ONE 
    boost::function<void (some_class, int) > f; 
    // initilize f with a member function of some_class 
    f = &some_class::do_stuff; 
    // pass an instance of some_class in order to access class member 
    f(some_class(), 5); 

    //    CASE TWO 
    boost::function<void (int) > f2; 
    // initialize f2 with a function object of other_class 
    f2 = other_class(); 
    // Note: directly call the operator member function without 
    // providing an instance of other_class 
    f2(10); 
} 


// output 
~/Documents/C++/boost $ ./p327 
some_class i: 5 
other_class i: 10 

問題>當我們調用通過升壓::功能的函數對象,爲什麼我們沒有提供一個實例的類來調用這個類的成員函數?爲什麼叫有增強函數對象::功能時不需要類實例

是否因爲我們通過以下方式提供了這些信息?

f2 = other_class(); 

回答

7

您必須爲類提供一個實例,並且您正在提供一個實例。

boost::function<void (int) > f2; 
f2 = other_class(); 

此構造一個other_class對象,並且該對象分配給f2boost::function然後複製該對象,以便在嘗試調用它時,不需要再次實例化它。

+2

它創建一個副本;在位構建的對象是一個臨時的右值,在語句結尾處無效。 – bdonlan 2011-12-31 20:09:05

+0

@bdonlan謝謝,我已經更新了我的答案。我不確定boost :: function是如何實現的,但是你是對的,C++基本上不允許任何其他方式。 – hvd 2011-12-31 20:14:07

1

爲什麼我們不必爲類調用這個類的成員函數提供一個實例?

因爲你已經給了它一個。就在這裏:

f2 = other_class(); 

您創建了一個other_class實例,該實例f2副本到自身。 f2不存儲other_class::operator()函數;它存儲類實例本身。所以,當你這樣做:

f2(10); 

f2存儲在其中的實例。它相當於:

other_class()(10); 
+0

你指出'副本'是很好的。 – q0987 2011-12-31 20:01:33

相關問題