C++类的内存分布
C++一般类的内存分布
一下都是在x64下进行的编译
1、空类
2、无继承、无虚函数类
3、无继承、有虚函数类
4、有继承、有虚函数类
C++继承类的内存分布
C++多重继承时的内存分布
#include <iostream> using namespace std; class A { public: int a; }; class B1 : public A { public: int b1; }; class B2 : public A { public: int b2; }; class C : public B1, public B2 { public: int c1; }; int main() { cout << "A_size=" << sizeof(A) << endl; cout << "B1_size=" << sizeof(B1) << endl; cout << "B2_size=" << sizeof(B2) << endl; cout << "C_size=" << sizeof(C) << endl; cout << "end..." << endl; system("pause"); return 0; }
类A、B1、B2的内存分布
类C的内存分布
C++类虚继承时的内存分布---->虚继承解决二义性的问题
#include <iostream> using namespace std; class A { public: int a; }; class B1 : virtual public A { public: int b1; }; class B2 : virtual public A { public: int b2; }; class C : public B1, public B2 { public: int c1; }; int main() { C c1; c1.b1 = 100; c1.b2 = 200; c1.c1 = 300; c1.a = 500; //虚继承使得成员变量a只有一份拷贝,通过虚指针可以确定地址 cout << "A_size=" << sizeof(A) << endl; cout << "B1_size=" << sizeof(B1) << endl; cout << "B2_size=" << sizeof(B2) << endl; cout << "C_size=" << sizeof(C) << endl; cout << "end..." << endl; system("pause"); return 0; }
类A和B1的内存分布
类B2的内存分布
类C的内存分布
等风起的那一天,我已准备好一切