2011-12-31 11 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オブジェクトを構築し、f2にそのオブジェクトを割り当てます。 boost::functionはそのオブジェクトをコピーするので、呼び出すまでにもう一度インスタンス化する必要はありません。

+2

コピーを作成します。インプレースで構築されたオブジェクトは、ステートメントの終わりに無効な値の一時的な値です。 – bdonlan

+0

@bdonlanありがとう、私は私の答えを更新しました。 boost :: functionが実装されているかどうかはわかりませんでしたが、正しいですが、C++は基本的にそれを他の方法で許可していません。 – hvd

1

なぜこのクラスメンバ関数を呼び出すためにクラスにインスタンスを提供する必要はありませんか?

あなたはすでに1つを与えているので。右ここに:

f2 = other_class(); 

あなたはf2自身のコピーにother_classインスタンスを作成しました。 f2other_class::operator()関数を格納しません。クラスインスタンス自体を格納します。だから、やるとき:

f2(10); 

f2は、その中に保存されたインスタンスをています。

other_class()(10); 
+0

あなたは 'コピー'を指摘しておいてよかったです。 – q0987

関連する問題