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

发布于 2024-10-03 12:25:35 字数 716 浏览 4 评论 0原文

我有以下类:

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

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

and pointer to the member function declared in another class:

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

How to declare/initlialize pointer to the member function for:

1] static class member function

Process.h

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

2] non class member function

Process.h

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

class Process
{
   private:
      ...
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

守不住的情 2024-10-10 12:25:35

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

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

您可以提供一个初始化程序:

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

The only thing you haven't done is to qualify the name of the function with the class name that it is a member of. Instead of providing a definition of Process::getCoord you've declared a global pointer-to-member called getCoord.

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

You can provide an initializer:

double ( Point2D::* Process::getCoord ) () const = &Point2D::getX;
妄司 2024-10-10 12:25:35

根据常见问题解答,最好使用typedef

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

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

初始化:

Process::getCoord = &Point2D::getX;

According to the FAQ it's best to use typedef:

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

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

Initialization:

Process::getCoord = &Point2D::getX;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文