2010-11-18 174 views
3
I have the following class: 

class Point2D 
{ 
    protected: 

      double x; 
      double y; 
    public: 
      double getX() const {return this->x;} 
      double getY() const {return this->y;} 
    ... 

};指向成員函數的指針

有時我需要返回x座標,有時是y座標,所以我使用了指向成員函數getX(),getY()的指針。但我不能回覆座標,請看下面。

double (Point2D :: *getCoord)() const; 

class Process 
{ 
    ...... 
    public processPoint(const Point2D *point) 
    { 

     //Initialize pointer 
     if (condition) 
     { 
     getCoord = &Point2D::getX; 
     } 
     else 
     { 
     getCoord = &Point2D::getY; 
     } 

     //Get coordinate 
     double coord = point->(*getCoordinate)(); //Compiler error 

    } 

} 

感謝您的幫助。

+0

對於稍微複雜的情況下,我將使用狀態(狀態模式),但對於這一點,似乎還好(現詹姆斯已經給出瞭解決方案) – stefaanv 2010-11-18 16:26:16

回答

6

您需要使用->*運營商通過指針調用一個成員函數:

(point->*getCoordinate)();