【问题标题】:C++ pointer to member function, declarationC++ 指向成员函数的指针,声明
【发布时间】:2010-11-20 18:21:45
【问题描述】:

我有以下课程:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    你可以提供一个初始化器:

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

    【讨论】:

    • 谢谢,我倒序写了: double ( Process::Point2D::* getCoord ) () const = &Point2D::getX;
    【解决方案2】:

    根据FAQ最好使用typedef

    typedef double (Point2D::*Point2DMemFn)() const;
    
    class Process
    {
          static Point2DMemFn getCoord;
          ...
    };
    

    初始化:

    Process::getCoord = &Point2D::getX;
    

    【讨论】:

    • Process::getCoord = &Point2D::getX; 不是一个有效的定义(或声明),因为没有类型,它只是一个赋值表达式,所以在你拥有它的地方无效。它应该是一个定义吗?
    • 问题是如何声明/初始化指针getCoord。我先写了怎么声明,然后怎么初始化。
    • 您已更改声明,但我没有看到定义(缺少定义可能是问题中链接错误的原因)或初始化(分配不一样作为初始化),也许我不明白你想展示什么?
    • 我试图回答这个问题。如果 OP 对答案不满意,他可以要求澄清。
    • 对不起,我显然没有说清楚。我只是想帮助这个更好的答案。您标记为“初始化:”的东西只是一个任务。如果这就是您的意图,那么您可能应该明确表示它需要在函数中。例如void init() { Process::getCoord = &Point2D::getX; } 。提问者仍然需要在函数或类定义之外的某个地方定义这个静态成员(例如Point2DMemFn Process::getCoord;),他也可以提供一个初始化程序(例如Point2DMemFn Process::getCoord = &Point2D::getX;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多