指针指向C 中的类方法

Pointer to a class method in c++

本文关键字:类方法 指针      更新时间:2023-10-16

A有很多B类,A类具有一个对象b。该对象b具有一个函数(calc),需要在A的对象中指向方法的指针。此方法(有趣的)ACESS私有变量(在我的示例中,只需返回3)。

class A;
class B {
public:
  virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
};
class A {
  B* b;
public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run(){ return b->calc(&A::fun); };
};
int main() {
  B* b = new B();
  A a(b);
  a.run();
  return 0;
}

在B类中的calc方法的定义中,如何正确使用指针?

我收到此错误消息:

teste.cpp:10:58: error: must use ‘.*’ or ‘->*’ to call pointer-to-member     function in ‘fun (...)’, e.g. ‘(... ->* fun) (...)’
   virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
                                                      ^

如果对您来说是可行的,建议使用std::function方法。但是,为了完整,您将如何正确使用指针到会员功能。

指针到会员本身不会存储A的"当前"实例,因此您需要明确传递该实例。然后,您使用特殊->*(或.*)语法来调用它。

virtual int calc (A* value, int (A::*fun)())  {
  return 2 * (value->*fun)();
};

然后您将其称为b->calc(this, &A::fun);

您可以按照自己的方式进行操作,但是必须在特定实例上调用成员函数:

class A;
class B {
public:
    virtual int calc(A* a, int (A::*fun)()) { return 2 * (a->*fun)(); };
};
class A {
    B* b;
public:
    A(B* b_) : b(b_) {};
    int fun() { return 3; };
    int run() { return b->calc(this, &A::fun); }; // now also passing this pointer
};
int main() {
    B* b = new B();
    A a(b);
    a.run();
    return 0;
}

如果您可以在没有calc()的情况下生活,那么Lambda也是一个选择:

class A;
class B {
public:
    template<typename T>
    int calc(T fun) { return 2 * fun(); };
};
class A {
    B* b;
public:
    A(B* b_) : b(b_) {};
    int fun() { return 3; };
    int run() {
        return b->calc([this]() {return fun(); } );
    };
};
int main() {
    B* b = new B();
    A a(b);
    a.run();
    return 0;
}

将指针到类方法定义为(假设某些fn匹配签名):

):
RetType (ClassName::*pfn)(Args) = &ClassName::SomeFn;

,称为:

ClassName * ptr = GetClassPtr();
(ptr->*pfn)(arg, arg);

如果您能够使用C 11,则应使用std :: function and std :: bind:否则您需要使用指针来成员函数 一个指针实例。

带有C 11

#include <functional>
class B {
public:
  virtual int calc (std::function<int()>&& fun) { return 2 * fun();  }; };
};
class A {
  B* b;
public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run() { return b->calc(std::bind(&A::fun, this)); };
};

没有C 11

class B {
public:
  virtual int calc (int(A::*fnptr)(), A* a) { return 2 * (a->*fnptr)(); };
};
class A {
  B* b;
public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run() { return b->calc(&A::fun, this); };
};

请参见此处的示例。