如何在類定義中調用指針成員函數? 我的代碼:如何在類定義中調用指針成員函數?
//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++的新手,可能設計很奇怪!
保羅
你需要一個實例來調用它,有關於如何在這裏做這麼多重複。我還建議你閱讀['std :: function'](http://en.cppreference.com/w/cpp/utility/functional/function)和['std :: bind'](http:// en .cppreference.com /瓦特/ CPP /實用程序/功能/綁定)。 –
@JoachimPileborg從MyClass :: Execute中調用該實例。 –
@WojtekSurowka即使實例已知,在調用成員函數指針時也需要使用它。 –