首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >怎么通过函数指针调用C++类方法?

怎么通过函数指针调用C++类方法?
EN

Stack Overflow用户
提问于 2018-04-17 11:23:24
回答 2查看 0关注 0票数 0

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

class Dog : Animal
{
    Dog ();
    void bark ();
}

…
Dog* pDog = new Dog ();
BarkFunction pBark = &Dog::bark;
(*pBark) (pDog);
…

另外,如果可能的话,我想通过一个指针调用构造函数:

NewAnimalFunction pNew = &Dog::Dog;
Animal* pAnimal = (*pNew)();    

执行此操作的首选方法是什么?

EN

回答 2

Stack Overflow用户

发布于 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');
票数 0
EN

Stack Overflow用户

发布于 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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003901

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档