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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM