我最近遇到了一些非常奇怪的语法:
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;
}
虽然声明test不会给出任何错误和输出0 0 0
(我相信0只是巧合;由于struct是Plain Old Data,所以没有将其成员默认初始化为0),但通过将该声明更改为定义Test test();
会产生错误
tester.cpp:14:20: error: request for member 'a' in 'test', which is of non-class
type 'Test()'
启用C ++ 11会删除错误消息,但是值仍然神秘地保持为0。此语法实现了什么?
此语法是位字段。
struct Test {
size_t a : 2; // Occupies two bits
size_t b : 3; // Occupies three bits
size_t c : 4; // Occupies four bits
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句