【问题标题】:why both constructor of Base class and Drive class run when initialize instance of Drive class为什么初始化 Drive 类的实例时 Base 类和 Drive 类的构造函数都运行
【发布时间】:2012-06-08 07:47:57
【问题描述】:
#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。

【问题讨论】:

  • 您的问题是什么?根据我的推断,您需要阅读继承。
  • 是关于虚拟指针和vtable的。为什么我们只有 1 个虚拟指针但有 2 个 vtalbe?

标签: inheritance pointers constructor virtual vtable


【解决方案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;
    }

【讨论】:

  • 如果我只想驱动构造函数运行会有什么问题。我可以吗?
  • 是的,你可以通过不从基类继承
  • 不要继承 Base 类,否则 Base 的构造函数不会运行。
猜你喜欢
  • 2012-11-05
  • 2020-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多