2010-11-20 160 views
2

我有下面的类:C++成员函数指针,声明

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: 
     ... 
}; 

回答

1

按照FAQ,最好使用typedef

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

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

初始化:

Process::getCoord = &Point2D::getX; 
+0

'过程:: getCoord =的Point2D ::信息getX;'是不是一个有效的定义(或声明),因为没有类型,它只是一个分配表达式不适用于你拥有它的地方。它应该是一个定义吗? – 2010-11-20 21:18:07

+0

问题是如何声明/初始化指针getCoord。我首先写了如何声明它,然后如何初始化它。 – Dialecticus 2010-11-20 22:42:49

+0

你已经修改了声明,但我不明白的定义(缺少其中的可能是在问题的链接错误的原因)或初始化(分配是不一样的初始化),或许我不不明白你想表达什么? – 2010-11-21 00:14:07

2

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

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

你可以提供一个初始化:

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

谢谢,我写它以相反的顺序:双(进程: :Point2D :: * getCoord)()const =&Point2D :: getX; – Ian 2010-11-21 12:29:23