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、位段
快捷操作:
坚其志,苦其心,劳其力,事无大小,必有所成。
@如有侵权,请作者本人尽快与我(chrayo#163.com)联系,我将及时删除侵权内容。