[英]C++ pointer to member function, declaration
我有以下课程:
class Point2D
{
protected:
double x;
double y;
public:
double getX() const {return this->x;}
double getY() const {return this->y;}
...
};
和指向另一个类中声明的成员函数的指针:
double ( Point2D :: *getCoord) () const;
如何为以下成员声明/初始化指向成员函数的指针:
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:
...
};
您唯一要做的就是用该函数所属的类名来限定该函数的名称。 Process::getCoord
提供Process::getCoord
的定义,而是声明了一个名为getCoord
的全局成员指针。
double ( Point2D::* Process::getCoord ) () const;
您可以提供一个初始化程序:
double ( Point2D::* Process::getCoord ) () const = &Point2D::getX;
根据常见问题解答 ,最好使用typedef
:
typedef double (Point2D::*Point2DMemFn)() const;
class Process
{
static Point2DMemFn getCoord;
...
};
初始化:
Process::getCoord = &Point2D::getX;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.