我正在尝试使用虚函数表通过索引在类中调用函数... 假设我们有以下代码:
class Base
{
public:
Base() {}
virtual ~Base() {}
virtual Base* call_func(unsigned int func_number)
{
// Some way to call f_n
}
protected:
virtual Base* f_1() const = 0;
virtual Base* f_2() const = 0;
virtual Base* f_3() const = 0;
};
我已经使用函数数组、if语句和case语句实现了这个功能...所以,有没有更好的方法只使用指针来调用方法(例如访问虚表)或类似的东西?
抱歉我的英语很糟糕 :S...提前感谢!
编辑: 感谢所有建议!我将扩展我的问题:
解决这个问题后,我将创建派生类(例如derived1和derived2),它们具有不同的f_1、f_2、f_3实现,并拥有一个类控制器如下:
class Control
{
protected:
Base* current;
public:
Control(Base* curr = new derived1): current(curr) {}
virtual ~Control()
{
delete current;
}
virtual void do_something(unsigned int func_numb)
{
delete current
Base* new = current->next_state(stl);
current = new;
}
};
func_number
索引到我们已知的指针表中(在所有常见的实现中都是如此)。可惜,我认为没有这种方法。因为你需要虚拟调用,所以只能使用if
或switch
。 - Nicholas Wilson