通过函数指针调用C ++类方法 [英] Calling C++ class methods via a function pointer
本文介绍了通过函数指针调用C ++类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取类成员函数的函数指针,然后使用特定对象调用该成员函数?我想写:
class Dog:Animal
{
Dog
void bark();
}
...
狗* pDog = new Dog();
BarkFunction pBark =& Dog :: bark;
(* pBark)(pDog);
...
此外,如果可能,我想通过指针调用构造函数
NewAnimalFunction pNew =& Dog :: Dog;
Animal * pAnimal =(* pNew)();这是可能的吗?如果是这样,这是最好的方法是什么?
解决方案阅读此详细:
// 1定义函数指针并初始化为NULL
int(TMyClass :: * pt2ConstMember)(float,char,char)const = NULL;
// C ++
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; };
/ * TMyClass的更多* /
};
pt2ConstMember =& TMyClass :: DoIt; // note:< pt2Member>也可以合法地指向& DoMore
//使用函数指针调用函数
(* this。* pt2ConstMember)(12,'a','b');
How do I obtain a function pointer for a class member function, and later call that member function with a specific object? I’d like to write:
class Dog : Animal
{
Dog ();
void bark ();
}
…
Dog* pDog = new Dog ();
BarkFunction pBark = &Dog::bark;
(*pBark) (pDog);
…
Also, if possible, I’d like to invoke the constructor via a pointer as well:
NewAnimalFunction pNew = &Dog::Dog;
Animal* pAnimal = (*pNew)();
Is this possible, and if so, what is the preferred way to do this?
解决方案 Read this for detail :
// 1 define a function pointer and initialize to NULL
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;
// C++
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');
这篇关于通过函数指针调用C ++类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文