C++.类方法指针

Nik*_*ita 9 c++ methods pointers class

有一节课

class A {
public:
    A() {};

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


};
Run Code Online (Sandbox Code Playgroud)

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

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

我该怎么做?

sbi*_*sbi 8

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) {};
};
Run Code Online (Sandbox Code Playgroud)

也就是说,多态性可能是一种更好的方式来做任何你想做的事情.

  • @Cippyboy:我甚至不确定要回复什么.你煞费苦心地评价,但是没有解决这个微不足道的错误?!好吧,猜猜看,我现在把它留在那里,只是为了惹恼你. (2认同)

jpa*_*cek 5

添加成员变量

void (A::*ptr)();
Run Code Online (Sandbox Code Playgroud)

在构造函数中设置它

ptr=&A::func1;
Run Code Online (Sandbox Code Playgroud)

(或使用初始化列表)并在A的方法中调用它:

(this->*ptr)();
Run Code Online (Sandbox Code Playgroud)