[C/C++不常见语法特性]_[位域的使用细节]

2014-11-24 12:30:27 · 作者: · 浏览: 1


场景:

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

参考: 《C++ Primer 3rd Edition》