2014-07-04 63 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]);