C++对象数据成员存储示例


本文主要以示例说明C++对象数据成员存储布局,有关理论知识,请参考Data语意学

一、数据成员的布局

1.1、无继承

#include <iostream>
using namespace std;

class X
{
   
public:
    int a = 0;
    static int staticx;
    int b = 1;
};
int X::staticx = 42;

class Y
{
   
public:
    int a = 0;
    static int staticy;
public:
    int b = 1;
};
int Y::staticy = 43;

int main()
{
   
    X x;
    cout << "X:" << endl;
    cout << "sizeof(X) = " << sizeof(X) << endl;
    cout << "vptr address: " << (&x) << endl;
    cout << "x.a address: " << &x.a << endl;
    cout << "x.b address: " << &x.b << endl;
    cout << "x.staticx address: " << &x.staticx << endl;

    Y y;
    cout << "\nY:" << endl;
    cout << "sizeof(Y) = " << sizeof(Y) << endl;
    cout << "vptr address: " << (&y) << endl;
    cout << "y.a address: " << &y.a << endl;
    cout << "y.b address: " << &y.b << endl;
    cout << "y.staticy address: " << &y.staticy << endl;

    return 0;
}

程序运行结果如下:

在这里插入图片描述
从上述结果可以看出:非静态数据成员在类对象中的排列顺序将和其被声明的顺序一样,任何中间介入的静态数据成员都不会被放进对象布局之中。在上述例子中,X和Y对象是由两个int组成的,顺序是a、b。

C++标准要求,在同一个access section(也就是private、public、protected等区段)中,成员的排列只需符合"较晚出现的成员在类对象中有较高的地址"这一条即可。

C++编译器也允许编译器将多个access section之中的数据成员自由排列,不必在乎它们出现在类声明中的顺序。

1.2、单一继承

#include <iostream>
using namespace std;

class X
{
   
public:
    int ax = 0;
    static int staticx;
    int bx = 1;
    char cx = 'a';
};
int X::staticx = 42;

class Y :public X
{
   
public:
    int ay = 0;
    static int staticy;
public:
    int by = 1;
};
int Y::staticy = 43;

int main(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值