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)
也就是说,多态性可能是一种更好的方式来做任何你想做的事情.
添加成员变量
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)