将常见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
