2011-12-31 63 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

相关问题