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

问题描述

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

I'm trying to use the virtual method table to call functions by index ina class... Suppose we have the following code:

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语句实现了这一点和案例陈述...所以,有没有更好的方法来调用方法仅使用指针(例如访问vtable)还是类似的东西?

I've already implemented this using function arrays, if-statementand case-statement... so, Is there a a better approach to call methodsusing just pointers (accessing to the vtable for example) or something like that?

对不起,我的英语太糟糕了:S ...,谢谢您!

Sorry for my horrible English :S... and thanks in advance!

感谢您的所有建议!我要扩大我的问题:

Thanks for all the suggestion! I'm going to expand my question:

解决此问题后,我将创建派生类(例如,derived1和derived 2)具有f_1,f_2,f_3的不同实现,并具有如下所示的类控件:

After resolve this i'm going to create derived classes (for example derived1 and derived 2)with different implementations of f_1, f_2, f_3 and have a class control like this:

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;
    }
};

推荐答案

我假设您只是想找到所有可能的解决方法.

I assume you just want to find all possible ways to solve it.

您可以使用指向成员函数的指针的映射(或向量),并将它们初始化一次(在构造函数中或以静态方式).那可以模拟vtable.

You can use map (or vector) of pointers to member functions and initialize them once (in constructor or statically). That can emulate the vtable.

这些行之间的内容:

class Base
{
public:
    Base() {
        functions.insert(std::make_pair(1,&Base::f_1));
        functions.insert(std::make_pair(2,&Base::f_2));
        functions.insert(std::make_pair(3,&Base::f_3));
        }
    virtual ~Base() {}
    virtual Base* call_func(unsigned int func_number)
    {
    return (this->*functions[func_number])();
}
protected:
    std::map<unsigned int, Base*(Base:: *)()const> functions;
virtual Base* f_1() const = 0;
virtual Base* f_2() const = 0;
virtual Base* f_3() const = 0;

};

这甚至对于继承的类也应该起作用(尽管我会将call_func设为非虚拟).是的,您应该检查该项目是否确实在地图(或矢量)中,以及它是否不是nullptr.

This should work even for inherited classes (I would make call_func non-virtual, though).And yes, you should check if the item really is in the map (or vector) and if it's not a nullptr.

这篇关于C ++:访问虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:38