C ++指向成员函数的指针,声明

时间:2010-11-20 18:21:46

标签: c++ declaration member-function-pointers

我有以下课程:

class Point2D
{
protected:

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

和指向另一个类中声明的成员函数的指针:

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

如何声明/ initlialize指向成员函数的指针:

1]静态类成员函数

Process.h

class Process
{
   private:
      static double ( Point2D :: *getCoord) () const; //How to initialize in Process.cpp?
      ...
};

2]非班级成员函数

Process.h

double ( Point2D :: *getCoord) () const; //Linker error, how do declare?

class Process
{
   private:
      ...
};

2 个答案:

答案 0 :(得分:3)

您唯一没有做的就是使用它所属的类名来限定函数的名称。您没有提供Process::getCoord的定义,而是声明了一个名为getCoord的全局指针成员。

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

您可以提供初始值设定项:

double ( Point2D::* Process::getCoord ) () const = &Point2D::getX;

答案 1 :(得分:1)

根据FAQ,最好使用typedef

typedef double (Point2D::*Point2DMemFn)() const;

class Process
{
      static Point2DMemFn getCoord;
      ...
};

初​​始化:

Process::getCoord = &Point2D::getX;
相关问题