如何在类定义中调用指针成员函数? 我的代码:如何在类定义中调用指针成员函数?
//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即使实例已知,在调用成员函数指针时也需要使用它。 –