首页 > 解决方案 > vptr调用虚函数

问题描述

我最近在阅读有关 C++ 中的虚函数和继承的内容,最后读到了 vptr 和 VTABLE。

我的问题与使用 vprt 调用派生对象的方法有关。

我解释一下,下面是我的代码:

    #include <iostream>
    using namespace std;


    class base
    {
    public:
        void fun_1() { cout << "base-1\n"; }
        virtual void fun_2() { cout << "base-2\n"; }
        virtual void fun_3() { cout << "base-3\n"; }
        virtual void fun_4() { cout << "base-4\n"; }
    };

    class derived : public base
    {
    public:
        void fun_1() { cout << "derived-1\n"; }
        void fun_2() { cout << "derived-2\n"; } 
        void fun_4() { cout << "derived-4\n"; }
    };

    int main()
    {
        base *p;
        derived obj1;
        p = &obj1;

        void(*firstfunc)() = (void(*)(void))(*(int*)*(int*)p);
        firstfunc();
    }

结果是:

衍生-2

好的,到目前为止,(void(*)(void))(*(int*)*(int*)p)我的脑海中仍然模糊不清,我该怎么做才能调用第二个函数?

谢谢

标签: c++polymorphismvirtual

解决方案


how could I do to call the second function ?

You would call it like this:

p->fun_2();

prints:

derived-2

Virtual tables and virtual function pointers are implementation details of your compiler. In general you should not care about such implementation details, because if you do you write non-portable code. Actually I am not even sure if your code has undefined behaviour or not, if it does then even a compiler that does place the vpointer at the place you expect could print garbage. Anyhow, dont do it, unless you need to, which is actually never ;).

As a sidenote, function pointers loose lots of their scariness if you use aliases, eg

using base_mem_fun = void (base::*)();
base_mem_fun first_base = &base::fun_1;
(p->*first_base)();

prints:

base-1

推荐阅读