c++ - 调用虚拟方法的不同方式

标签 c++ class methods virtual

<分区>

Possible Duplicate:
C++: Accessing Virtual Methods

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

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)或类似的东西?

解决这个问题后,我将创建派生类(例如 derived1 和 derived 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 call_functions(unsigned int func_numb)
    {
        delete current
        Base* new = current->call_func(func_numb);
        current = new;
    }
};

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

最佳答案

C++ 没有很好的内省(introspection)机制,也就是说,您可能知道,您不能在运行时按名称查找成员函数并从命名查找中调用它。但是你可以创建一个成员函数指针表;例如,参见 C++ FAQ Lite 条目中的示例 How do I create and use an array of pointer-to-member-function? . (我希望这与您已经提到的“函数数组”不同,但它似乎确实是完成您想要的事情的最佳方式。)

如果我可能会问,为什么你需要通过索引调用函数?虚函数通常存在以使用其自己的任务参数集来完成特定任务。

如果您要更直接地访问 vtable,您可能会做一些工作,但它会很脆弱且不可移植。

关于c++ - 调用虚拟方法的不同方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13842096/

相关文章:

Java 数据库和结果集

.net - 对集合使用get_Keys()方法是否正确

function - Apache 速度 : How to define a custom method like in Java?

arrays - Ruby——当我调用一个数组的方法时,是否需要将方法中的参数指定为数组的名称?

c++ - 操作数据成员时 : which of the following is considered best practice

c++ - 如何让 Windows Mobile 模拟器上的文件夹共享工作

javascript - 在 javascript 类中设置回调函数

php - 在 PHP 中转换自定义类的最佳方法是什么

c++ - 如何定义函数模板中使用的函数?

c++ - 糟糕 : the __cmp__ function