C++中sizeof()介绍

将常见sizeof()考核点汇总如下,细则可参考文末链接,可先浏览以下示例。

 

#include <stdio.h>

#include <stdlib.h>

#include <iostream>

using namespace std;

 

class A{};

class A1{
void test1();
};
class A2{
virtual void test();
};

class B

{

public:

    int a;

    double b;

private:

    int setValue();

};

class C:public B

{

public:

    int s;

   

};

class D:public B,public A

{

public:

    int s;

    int ch;

};

 

struct stTestA

{

    int a;

    char b;

};

 

struct stTestB

{

    char a;

    double b;

};

 

struct stTestC

{

    int a;

    double b;

    short c;

};

 

struct stTestD

{

    char a;

    int b;

    double c;

};

 

void main()

{

    cout<<sizeof(char)<<endl;    //1

    cout<<sizeof(short)<<endl;   //2

    cout<<sizeof(int)<<endl;    //4

    cout<<sizeof(float)<<endl;   //4

    cout<<sizeof(double)<<endl;  //8

    cout<<sizeof(A)<<endl;        //1 空类为占用字节为1

 cout<<sizeof(A1)<<endl;    //1 普通函数不计

    cout<<sizeof(A2)<<endl;    //4 虚函数表指针 4字节

    cout<<sizeof(B)<<endl;    //16 字节对齐

    cout<<"C:"<<sizeof(C)<<endl;    //24

    cout<<"D:"<<sizeof(D)<<endl;    //24

    cout<<sizeof(stTestA)<<endl;    //8

    cout<<sizeof(stTestB)<<endl;    //16

    cout<<sizeof(stTestC)<<endl;    //24

    cout<<sizeof(stTestD)<<endl;    //16   字节对齐细则 体会例子间差别

    cout<<sizeof(std::string)<<endl;    //32  与编译器及环境有关

    string *p;

    cout<<sizeof(p)<<endl;        //4 任何指针都是4(32bit环境)或8(64bit环境)

}

 

参考文档

https://www.cnblogs.com/bigbigtree/p/3580585.html

 

转载于:https://www.cnblogs.com/willowcc1803/p/10149345.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值