人较笨且记性不好,故记录在此.折叠代码打不开请F5.本博中很多是转载收录其他网友的文章(原文地址请见博文末尾),所有权为原作者所有!!!
此博客已不再更新和维护,欢迎关注我的github新博客

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: :: 管理 ::
 1 #include <stdio.h>
2
3 struct MyStruct
4 {
5 int a;
6 MyStruct();
7 }
8
9 MyStruct::MyStruct()
10 {
11 a =10;
12 }
13
14 void main(void)
15 {
16 MyStruct test;
17 printf("%d\n", test.a);
18 }

  最后结果是:10

  另外,将上述代码修改如下:

 1 #include <stdio.h>
2
3 struct MyStruct
4 {
5 int a:4; // 注意!!!
6 MyStruct();
7 }
8
9 MyStruct::MyStruct()
10 {
11 a =10;
12 }
13
14 void main(void)
15 {
16 MyStruct test;
17 printf("%d\n", test.a);
18 }

  最后结果:-6
  对于第一段代码的理解,然后你应该明白第二段代码中是因为"int a:4" 中":4"起作用了。
  这里,“4” 限制了(int)a的范围为“2^4-1”,即为“-8~7”,超过这个范围则会从头开始。

-----------------------------------------------------------------------
更正:在后面的学习过程中发现这种结构体初始化其实就是“位段” 。 (2012年3月28日 21:02:30)

【参考资料 感谢作者】
1、http://topic.csdn.net/u/20090725/21/3310fdf5-f60f-4541-a98d-c629ad92a3a4.html 
2、位段 

 

posted on 2011-08-31 21:24  子坞  阅读(1009)  评论(2编辑  收藏  举报