如何制作指向派生类的成员函数的指针
how to make pointers to a member-function of a derived class
我需要在基类中有一个函数指针数组,并定义这个数组指向子类中的函数,如下所示:
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)
}
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法