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的内存分布

 

posted @   知道了呀~  阅读(1149)  评论(4编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2019-07-04 hdu 1251 统计难题 前缀出现次数
点击右上角即可分享
微信分享提示