结构体大小问题

1.关于struct的大小

1.1 struct内包含数据成员时,该结构体的大小为结构体内数据成员的大小之和。有时候编译器也会增加字节使得边界整齐;

1.2 struct内不包含数据成员和函数时,结构体大小为1,有相应的内存起始地址;

1.3 struct 内只有函数时,结构体大小为1,有相应的内存起始地址。

#include <iostream>
using namespace std;
class A
{
 void print();
};
void A::print()
{
 cout<<"struct A"<<endl;
}
struct B
{
 int b;
};
struct C
{};
int main()
{
        A a;
        B b;
        C c;
        cout<<"sizeof(A):"<<sizeof(A)<<endl;
        cout<<"sizeof(B):"<<sizeof(B)<<endl;
        cout<<"sizeof(C):"<<sizeof(C)<<endl;
        cout<<"address of a:"<<(unsigned long )&a<<endl;
        cout<<"address of b:"<<(unsigned long )&b<<endl;
        cout<<"address of c:"<<(unsigned long )&c<<endl;

        return 0;
}

运行结果:

  

原文地址:https://www.cnblogs.com/liujiangyi/p/2628482.html