带有虚函数的类的sizeof

#include <iostream>
#include <cstdio>
using namespace std;

class A
{
public:
        char ach[3];
        virtual void test() { };
};

class B : public A
{
public:
        char bch[3];
        virtual void btest() { };
};

class C : public A
{
        char cch[3];
        virtual void ctest() { };
};

class D : public B, public C
{
        char dch[3];
        virtual void dtest() { };
};

int main()
{
        cout << sizeof(A) << endl;      // 8  = 1 * 4(char) + 1 * 4(virtual table)
        cout << sizeof(B) << endl;      // 12 = 2 * 4(char) + 1 * 4(virtual table,基类)
        cout << sizeof(C) << endl;      // 12 = 2 * 4(char) + 1 * 4(virtual table,基类)
        cout << sizeof(D) << endl;      // 28 = 5 * 4(char) + 2 * 4(virtual table,两个基类)

        return 0;
}
 

 

#include <iostream>
#include <cstdio>
using namespace std;

class A
{
public:
        char ach[3];
        virtual void test() { };
};

class B : virtual public A
{
public:
        char bch[3];
        virtual void btest() { };
};

class C : virtual public A
{
        char cch[3];
        virtual void ctest() { };
};

class D : virtual public B, virtual public C
{
        char dch[3];
        virtual void dtest() { };
};

int main()
{
        cout << sizeof(A) << endl;      // 8
        cout << sizeof(B) << endl;      // 16
        cout << sizeof(C) << endl;      // 16
        cout << sizeof(D) << endl;      // 32

        return 0;
}
 

 

 

你可能感兴趣的:(C++,c,C#)