如何获取类成员函数的函数指针,然后使用特定的对象调用该成员函数?
class Dog : Animal
{
Dog ();
void bark ();
}
…
Dog* pDog = new Dog ();
BarkFunction pBark = &Dog::bark;
(*pBark) (pDog);
…
另外,如果可能的话,我想通过一个指针调用构造函数:
NewAnimalFunction pNew = &Dog::Dog;
Animal* pAnimal = (*pNew)();
执行此操作的首选方法是什么?
发布于 2018-04-17 20:03:01
阅读这个:
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;
class TMyClass
{
public:
int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
int DoMore(float a, char b, char c) const
{ cout << "TMyClass::DoMore" << endl; return a-b+c; };
/* more of TMyClass */
};
pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore
// Calling Function using Function Pointer
(*this.*pt2ConstMember)(12, 'a', 'b');
发布于 2018-04-17 20:51:36
以typedef开头最简单。对于成员函数,需要在类型声明中添加类名称:
typedef void(Dog::*BarkFunction)(void);
可以使用该->*
运算符:
(pDog->*pBark)();
我已经修改了你的代码来做你基本上描述的内容。下面有一些注意事项。
#include <iostream>
class Animal
{
public:
typedef Animal*(*NewAnimalFunction)(void);
virtual void makeNoise()
{
std::cout << "M00f!" << std::endl;
}
};
class Dog : public Animal
{
public:
typedef void(Dog::*BarkFunction)(void);
typedef Dog*(*NewDogFunction)(void);
Dog () {}
static Dog* newDog()
{
return new Dog;
}
virtual void makeNoise ()
{
std::cout << "Woof!" << std::endl;
}
};
int main(int argc, char* argv[])
{
// Call member function via method pointer
Dog* pDog = new Dog ();
Dog::BarkFunction pBark = &Dog::makeNoise;
(pDog->*pBark)();
// Construct instance via factory method
Dog::NewDogFunction pNew = &Dog::newDog;
Animal* pAnimal = (*pNew)();
pAnimal->makeNoise();
return 0;
}
https://stackoverflow.com/questions/-100003901
复制相似问题