Skip to content

Instantly share code, notes, and snippets.

@raytroop
Created November 6, 2019 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raytroop/a9822c32faab52720060e33b267955d2 to your computer and use it in GitHub Desktop.
Save raytroop/a9822c32faab52720060e33b267955d2 to your computer and use it in GitHub Desktop.
c++ virtual inheritance
#include<iostream>
using namespace std;
//大小为4
class A
{
public:
int a;
};
//在64位环境下,变量a 4个字节,b 8个字节,虚基类表指针8个字节,为了对齐,大小总共24
class B :virtual public A
{
public:
double b;
};
//与B一样
class C :virtual public A
{
public:
double c;
};
//在64位环境下,大小为48,变量a 4,b 8,c 8,d 8加对齐共 32,B的虚基类指针 8,C的虚基类指针 8
class D :public B, public C
{
public:
double d;
};
int main()
{
cout << "int size: " << sizeof(int) << endl;
cout << "double size: " << sizeof(double) << endl;
cout << "pointer size: " << sizeof(void*) << endl;
cout << "---------------------------" << endl;
cout << "objec A: " << sizeof(A) << endl;
cout << "objec B: " << sizeof(B) << endl;
cout << "objec C: " << sizeof(C) << endl;
cout << "objec D: " << sizeof(D) << endl;
return 0;
}
/* int size: 4
double size: 8
pointer size: 8
---------------------------
objec A: 4
objec B: 24
objec C: 24
objec D: 48 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment