cao*_*ang 1 c++ virtual inheritance pointers vtable
#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;
Run Code Online (Sandbox Code Playgroud)
}
这个程序的输出是
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
Run Code Online (Sandbox Code Playgroud)
按照代码,我可以看到,当我创建一个Drive对象时,Base构造函数也运行并显示与Drive的虚拟指针相同的虚拟指针的地址:0012FF7C.奇怪的是,当我在Base和Drive类的构造函数中取消引用该地址时,它指向不同的值意味着有两个vtable,一个在0046C08C,另一个在0046C07C.当1指针指向2地址时,它很难理解Drive对象的结构以及c langue.
随着对象构造的发生,它会逐步发生.第一步是初始化基类,在该过程中对象是基础对象--vtable将反映基类的方法.当构造进行到派生类时,vtable将更新为派生类的vtable.
这些都是由C++标准规定的,当然标准不强制要求实现vtable.
| 归档时间: |
|
| 查看次数: |
1039 次 |
| 最近记录: |