成员函数指针

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

   }

}

感谢您的帮助。

对于稍微复杂的情况,我会使用状态(状态模式),但对于这种情况,似乎可以(现在James已经给出了解决方案)。 - stefaanv
1个回答

6
你需要使用->*运算符通过指针调用成员函数:
(point->*getCoordinate)(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接