C++ 如何生成指向派生类的成员函数的指针

C++ 如何生成指向派生类的成员函数的指针,c++,class,function-pointers,C++,Class,Function Pointers,我需要在基类中有函数指针数组,并定义此数组以指向子类中的函数,如下所示: 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_a

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

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\u cast

m_arf[0] = static_cast <A::Fn> (&B::get1);
唷,真是一团糟。最好不要以这种方式使用成员函数指针,除非必须这样做。不管怎样,这里有一个演示如何在这里完成

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)
}
A类{
公众:
typedef-double(A::*Fn)(int,int);
Fn*m_arf;
};
B类:公共A{
公众:
双get1(inti,intj)
{
返回i+j;
};  
双get2(整数i,整数j)
{
返回i-j;
};  
B(){
m_arf=新的Fn[2];
m_arf[0]=静态_cast(&B::get1);
m_arf[1]=静态_cast(&B::get2);
};  
};
int main()
{
A*pA=新的B;
int ires=(pA->*(pA->m_arf[0])(1,2);//返回B::get1(1,2)
int-ires1=(pA->*(pA->m_arf[1])(1,2);//返回B::get2(1,2)
}

Spooky!顺便说一句,你试过了吗?编译器说了什么?是哪个编译器?我想这就是虚拟类成员的用途。@RichardChambers:函数指针仍然有用途。@JohnDibling,是的,函数指针也有用途,我只是怀疑这是否是其中之一。@RichardChambers:对,我只是假设OP只是想弄清楚如何实现跳转表。
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)
}