C++:访问虚拟方法

2023-12-15

我正在尝试使用虚拟方法表按索引调用函数 一个类...假设我们有以下代码:

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-statement...那么,有没有更好的方法来调用方法 仅使用指针(例如访问 vtable)或类似的东西?

抱歉我糟糕的英语:S...并提前致谢!

编辑: 感谢您的所有建议!我要扩展我的问题:

解决这个问题后,我将创建派生类(例如派生1和派生2) 具有 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;
    }
};

一个 switch 语句:

switch (func_number)
{
    case 1:
        f_1();
        break;
    case 2:
        f_2();
        break;
    case 3:
        f_3();
        break;
}

或者使用函数指针数组。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++:访问虚拟方法 的相关文章

随机推荐