0
#include <iostream>
using namespace std;

class Base {
    public:
        Base() {
            cout << "In Base" << endl;
            cout << "Virtual Pointer = " << (int*)this << endl;
            cout << "Address of Vtable = "
            << (int*)*(int*)this << endl;
            cout << "Value at Vtable = "
            << (int*)*(int*)*(int*)this << endl;
            cout << endl;
        }

        virtual void f1() { cout << "Base::f1" << endl; }
};

class Drive : public Base {
    public:
        Drive() {
            cout << "In Drive" << endl;
            cout << "Virtual Pointer = "
            << (int*)this << endl;
            cout << "Address of Vtable = "
            << (int*)*(int*)this << endl;
            cout << "Value at Vtable = "
            << (int*)*(int*)*(int*)this << endl;
            cout << endl;
        }

        virtual void f1() { cout << "Drive::f2" << endl; }
};

int main() {
    Drive d;
    return 0;
}

这个程序的输出是

In Base
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C08C
Value at Vtable = 004010F0

In Drive
Virtual Pointer = 0012FF7C
Address of Vtable = 0046C07C
Value at Vtable = 00401217

在我看来,当我初始化 Drive 实例时,只运行 Drive 类的构造函数,但在这个程序中,Base 的构造函数中的代码也运行。跟随输出,有些奇怪,我们只有 1 个实例,1 个虚拟指针,但我们有 2 个 Vtable。

4

1 回答 1

1

因为当你运行继承类的构造函数时,它的超类的构造函数会自动运行。就像您的编译器在 Drive 构造函数的第一行中为您提供了对 Base 构造函数的呼吁。对于您的编译器,Drive 构造函数如下所示:

    Drive() {
        Base();
        cout << "In Drive" << endl;
        cout << "Virtual Pointer = "
        << (int*)this << endl;
        cout << "Address of Vtable = "
        << (int*)*(int*)this << endl;
        cout << "Value at Vtable = "
        << (int*)*(int*)*(int*)this << endl;
        cout << endl;
    }
于 2012-06-04T08:06:30.440 回答