C ++.类方法指针 [英] C++. Class method pointers

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

问题描述

有一堂课

class A {
public:
    A() {};

private:
    void func1(int) {};
    void func2(int) {};


};

我想添加一个函数指针,该指针将在构造函数中设置并指向func1或func2.

I want to add a function pointer which will be set in constructor and points to func1 or func2.

因此,我可以从每个类过程中调用此指针(作为类成员),并在构造函数中设置此指针.

So I can call this pointer (as class member) from every class procedure and set this pointer in constructor.

我该怎么办?

推荐答案

class A {
public:
    A(bool b) : func_ptr_(b ? &A::func1 : &A::func2) {};

    void func(int i) {this->*func_ptr(i);}

private:
    typedef void (A::*func_ptr_t_)();
    func_ptr_t_ func_ptr_;

    void func1(int) {};
    void func2(int) {};
};

也就是说, 多态性可能是您执行此操作所需的更好方法.

That said, polymorphism might be a better way to do whatever you want to do with this.

这篇关于C ++.类方法指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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