欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

图解C++ Vtable

程序员文章站 2022-05-07 22:38:28
...

下面给出一个完整的C++代码实例(结合图解,相信大家一定会真正理解多态思想):

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<iomanip>
using namespace std;
 
 
class A
{
public:
    int m_data1;
    int m_data2;
    void func1() {}
    void func2() {}
    virtual void vfunc1(){}
    virtual void vfunc2(){}
};
 
 
class B : public A
{
public:
    int m_data3;
    void func2() {}
    virtual void vfunc1(){}
};
 
 
class C : public B
{
public:
    int m_data1;
    int m_data4;
    void func2() {}
    virtual void vfunc1(){}
};
 
 
void main()
{
    cout << "sizeof(A):" << sizeof(A) << endl;
    cout << "sizeof(B):" << sizeof(B) << endl;
    cout << "sizeof(C):" << sizeof(C) << endl;
 
 
    A a;B b;C c;
    b.m_data1 = 1;
    b.m_data2 = 2;
    b.m_data3 = 3;
 
 
    c.m_data1 = 11;
    c.m_data2 = 22;
    c.m_data3 = 33;
    c.m_data4 = 44;
    c.A::m_data1 = 111;
 
 
 
 
    cout << "The offset of object b:" << endl;
    cout << &b << " : " << "vptr from A" << endl;
    cout << &(b.m_data1) << " : " << b.m_data1 << endl;
    cout << &(b.m_data2) << " : " << b.m_data2 << endl;
    cout << &(b.m_data3) << " : " << b.m_data3 << endl << endl;
 
 
    cout << "The offset of object c:" << endl;
    cout << &c << " : " << "vptr fron B" << endl;
    cout << &(c.A::m_data1) << " : " << c.A::m_data1 << endl;
    cout << &(c.m_data1) << " : " << c.m_data1 << endl;
    cout << &(c.m_data2) << " : " << c.m_data2 << endl;
    cout << &(c.m_data3) << " : " << c.m_data3 << endl;
    cout << &(c.m_data4) << " : " << c.m_data4 << endl << endl;
    system("pause");
}
 

原理解释:

图解C++ Vtable