字节对齐示例:

#include <iostream>
using namespace std;
// 外来人口信息
struct Foreigner
{
    Foreigner(double s, double ph) : addr(s), phone(ph) {}
    double addr;  // sizeof(double)=8
    double phone;
};

// 登记人口信息
class Person
{
public:
    enum class Category : char {Student, Local, Foreign};
    Person(int num) : number(num), type(Category::Student) {}
    Person(double id) : idNum(id), type(Category::Local) {}
    Person(double addr, double phone) : foreign(addr, phone), type(Category::Foreign) {}
    ~Person() {}

    void print()
    {
        cout << "Person category: " << (int)type << " sizeof:"<< sizeof(type) << endl;
        // cout << "number addr:"<< &number << " idNum addr:"<< &idNum << " foreign addr:" <<&foreign << endl;
        switch (type)
        {
        case Category::Student:
            cout << "Student school number: " << number << " sizeof:" << sizeof(number) << endl;
            break;
        case Category::Local:
            cout << "Local people ID number: " << idNum << " sizeof:" << sizeof(idNum) << endl;
            break;
        case Category::Foreign:
            cout << "Foreigner address: " << foreign.addr
                << ", phone: " << foreign.phone << " sizeof:" << sizeof(foreign) << endl;
            break;
        default:
            break;
        }
    }

private:
    Category type;  // 对齐最长字节8
    union   // 64字节
    {
        int number;
        double idNum;
        Foreigner foreign;  // 元素最宽为8,长度为16
    };
};

union test      // typeof(test) //16
{
    enum class Category : char {Student, Local, Foreign};
    test(int num) : number(num) {}
    ~test() {}
    test(double id) : idNum(id) {}
    test(double addr, double phone) : foreign(addr, phone) {}
    int number;
    double idNum;
    Foreigner foreign;
};

int main()
{
    Person p1(9527);
    Person p2(12.25);
    Person p3(16.5, 1.256);
    p1.print();
    p2.print();
    p3.print();
    cout << "sizeof:"<< sizeof(p3) << endl;     // sizeof:24
    test t(16.5, 1.256);
    cout << "union sizeof:"<< sizeof(t) << endl;    // union sizeof:16
    return 0;
}
// g++ std=c++11 test.cpp -o test
/*
Person category: 0 sizeof:1
Student school number: 9527 sizeof:4
Person category: 1 sizeof:1
Local people ID number: 12.25 sizeof:8
Person category: 2 sizeof:1
Foreigner address: 16.5, phone: 1.256 sizeof:16
sizeof:24
union sizeof:16
*/

原文地址:http://www.cnblogs.com/xiaohuidi/p/16922256.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性