2014-07-04 41 views
0

如何在類定義中調用指針成員函數? 我的代碼:如何在類定義中調用指針成員函數?

//Myclass.h 

struct Booking{ 
    int src; 
    int dest; 
    int pos; 
}; 

class MyClass{ 
public: 
    void ExecutePlan(); 
private: 
    struct FlightPlan{ 
     string name; 
     vector<Booking> bookings 
    }; 

    typedef FlightPlan FP; 
    FP firstplan; 
    FP secondplan; 
    void FirstPlan(Booking& book); 
    void SecondPlan(Booking& book); 
    void Execute(FP& fplan, void (MyClass::*mptr)(Booking& book)); 
}; 

// Myclass.cpp 
void MyClass::FirstPlan(Booking& book){ 
// do something with booking 
} 

void MyClass::SecondPlan(Booking& book){ 
// do something with booking 
} 

void MyClass::Execute(FP& fplan, void(MyClass::*mptr)(const FlightPlan& fp)){ 
    for (int i=0; i<.fplan.bookings.size(); i++){ 
     cout << "Executing Plan: "<< fplan.name << endl; 

     // Problematic line ... 
     mptr(bookings[i]); // <----- can't compile with this 
    } 
} 

void MyClass::Execute(){ 
// is this the correct design to call this member functions ??? 

    Execute(firstplan, &MyClass::FirstPlan) 
    Execute(secondplan, &MyClass::SecondPlan) 
} 

我怎麼能結構中的執行函數接收一個成員函數指針?

請問:我是C++的新手,可能設計很奇怪!

保羅

+0

你需要一個實例來調用它,有關於如何在這裏做這麼多重複。我還建議你閱讀['std :: function'](http://en.cppreference.com/w/cpp/utility/functional/function)和['std :: bind'](http:// en .cppreference.com /瓦特/ CPP /實用程序/功能/綁定)。 –

+0

@JoachimPileborg從MyClass :: Execute中調用該實例。 –

+0

@WojtekSurowka即使實例已知,在調用成員函數指針時也需要使用它。 –

回答

3

如何調指針成員函數的類定義中?

與成員名稱不同,成員指針不隱式應用於this。你必須要明確:

(this->*mptr)(fplan.bookings[i]); 

這是正確的設計來調用這個成員函數???

除了幾個明顯的錯誤(如缺少;在這裏和那裏,說const FlightPlan&,你的意思是在Execute定義Booking&),該代碼的其餘部分看起來很好。特別是

Execute(firstplan, &MyClass::FirstPlan) 
Execute(secondplan, &MyClass::SecondPlan) 

是獲取成員函數指針的正確語法。

+0

我越來越語法錯誤「class MyClass沒有名爲'mptr'的成員?? – gath

+0

@gath:這聽起來像你寫' - >'而不是' - > *' –

+0

實際上我正在使用 - > *,是我的Execute函數簽名正確無效MyClass :: Execute(FP&fplan,void(MyClass :: * mptr)(const FlightPlan&fp))? – gath

1

調用成員函數指針的操作符是->*。既然你要調用它this對象,你需要使用

(this->*mptr)(bookings[i]);