通过函数指针调用 C++ 成员函数 [英] Calling C++ member functions via a function pointer

查看:60
本文介绍了通过函数指针调用 C++ 成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取类成员函数的函数指针,然后使用特定对象调用该成员函数?我想写:

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?

推荐答案

阅读 this 详情:

// 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆