冒号后成员申报?

时间:2015-07-05 22:36:30

标签: c++ struct syntax

我最近遇到了一些非常奇怪的语法:

struct Test {
    size_t a : 2;
    size_t b : 3;
    size_t c : 4;
};

奇怪的是,这与GCC 4.9.2一起编译,所有警告标志都打开了。

void test_test() {
    Test test;
    std::cout << test.a << " " << test.b << " " << test.c << std::endl;
} 

虽然声明测试没有给出错误并输出0 0 0(我相信0只是巧合;因为结构是普通旧数据,它的所有成员都没有默认初始化为0),所以改变 通过Test test();对定义的声明给出了错误

tester.cpp:14:20: error: request for member 'a' in 'test', which is of non-class
 type 'Test()'

启用C ++ 11会删除错误消息,但值仍然会显示为0. 此语法实现了什么

1 个答案:

答案 0 :(得分:4)

此语法是位域。

struct Test {
    size_t a : 2; // Occupies two bits
    size_t b : 3; // Occupies three bits
    size_t c : 4; // Occupies four bits
};
相关问题