場景:
1.位域作為一個控制空間大小的語法特性其實是有它自己的用武之地的,比如網絡通訊的協議定制,使用位域為1來嚴格限制bool值為0,1等等.
2.它有一些細節需要注意,
第一: 位域的大小是值的類型的整數倍,不足整數倍的補全.如unsigned short的大小是16位,那麼如果總值17位的話會自動補全到16*2=32位.
第二: 賦值當然需要位運算符或者不超過它的最大值的整數.
代碼:
#include#include #include #include #include #include using namespace std; typedef unsigned int Bit; class NetData { public: Bit type: 1; Bit valid: 1; Bit delay_second: 4; Bit command: 4; Bit finished: 1; Bit error: 4; unsigned char t: 2; }; int main(int argc, char const *argv[]) { cout << "NetData size:" << sizeof(NetData) << endl; NetData nd; nd.type = 01; nd.valid = 00; nd.delay_second = 15; //如果是>15,gcc會有警告 warning: large integer implicitly truncated to unsigned type nd.command = 13; nd.finished = 1; nd.error = 2; cout << "nd.type: " << nd.type << endl << "nd.valid: " << nd.valid << endl << "nd.delay_second: " << nd.delay_second << endl << "nd.command: " << nd.command << endl << "nd.finished: " << nd.finished << endl << "nd.error: " << nd.error << endl << endl; return 0; }
輸出:
NetData size:4 nd.type: 1 nd.valid: 0 nd.delay_second: 15 nd.command: 13 nd.finished: 1 nd.error: 2