如何制作指向派生类的成员函数的指针

how to make pointers to a member-function of a derived class

本文关键字:成员 函数 指针 派生 何制作      更新时间:2023-10-16

我需要在基类中有一个函数指针数组,并定义这个数组指向子类中的函数,如下所示:

typedef double (_f)(int,int);
class A{
public:
  _f **m_arf;
};
class B:public A{
public:
  double get1(int i, int j) {return i+j};
  double get2(int i, int j) {return i-j};
B(){
     m_arf = new _f*[2];
     m_arf[0] = &get1;
     m_arf[1] = &get2;
   };
};

然后我可以做以下事情:

{
  A* pA = new B;
  int ires = pA->m_arf[0](1,2); // returns B::get1(1,2)
  int ires1 = pA->m_arf[1](1,2); // returns B::get2(1,2)
}

有可能吗?

指针:

typedef double (_f)(int,int);

不/不能指向成员函数。它只能指向自由函数所以你想做的事情永远不会像你想的那样奏效。

要声明成员函数指针,语法不同:

typedef double (A::*_f)(int,int);

此外,您还必须采用不同语法的指针:您必须引用类。

_f = &B::get1; // not &get1

但是,现在您将遇到另一个问题,即get1不是A的成员,而是B的成员。为了将指向派生类成员的指针分配给指向基类成员的指针,必须使用static_cast:

m_arf[0] = static_cast <A::Fn> (&B::get1);

最后,通过该指针进行atually调用的语法也有所不同。不能只通过指针直接调用,还必须将调用与类的实例相关联。->*语法将类实例连接到函数指针:

int ires = (pA->*(pA->m_arf [0])) (1,2);

哇,真是一团糟。除非迫不得已,否则最好不要以这种方式使用成员函数指针。无论如何,这里有一个演示。

class A{
public:
  typedef double (A::*Fn) (int, int);
  Fn *m_arf;
};
class B:public A{
public:
  double get1(int i, int j)  
  {
    return i+j;
  };  
  double get2(int i, int j)  
  {
    return i-j;
  };  
B(){
     m_arf = new Fn[2];
     m_arf[0] = static_cast <A::Fn> (&B::get1);
     m_arf[1] = static_cast <A::Fn> (&B::get2);
   };  
};
int main()
{
  A* pA = new B;
  int ires = (pA->*(pA->m_arf [0])) (1,2); // returns B::get1(1,2)
  int ires1 = (pA->*(pA->m_arf[1])) (1,2); // returns B::get2(1,2)
}