先来看一段程序:
#include <stdio.h>
typedef struct with_static
{
int a;
static const int b = 1;
}with_static;
int main()
{
struct with_static test1;
struct with_static test2;
test1.a = 1;
printf("test1.a = %d/n",test1.a);
printf("test1.b = %d/n",test1.b);
printf("test2.a = %d/n",test2.a);
printf("test2.b = %d/n",test2.b);
return 0;
}
标准的C/C++不伦不类程序,呵呵。
首先,此程序在VC2005下编译有2个结果
1.编译为 C 代码(/TC)
编译不通过。
正在编译...
test.c
./test.c(6) : error C2071: 'b' : illegal storage class
./test.c(6) : error C2143: syntax error : missing ';' before '='
./test.c(6) : error C2059: syntax error : '='
./test.c(7) : error C2059: syntax error : '}'
./test.c(11) : error C2079: 'test1' uses undefined struct 'with_static'
./test.c(12) : error C2079: 'test2' uses undefined struct 'with_static'
./test.c(14) : error C2224: left of '.a' must have struct/union type
./test.c(16) : error C2224: left of '.a' must have struct/union type
./test.c(17) : error C2224: left of '.b' must have struct/union type
./test.c(18) : error C2224: left of '.a' must have struct/union type
./test.c(19) : error C2224: left of '.b' must have struct/union type
C1005: Illegal storage class 非法使用的存储类型
2.编译为 C++ 代码(/TP)
编译通过,可以生成exe文件。
结论:
在C编译器下,结构体内不允许包含static变量。
原因:
1. C中struct只是类型声明,没有内存空间的分配,而static变量是需要分配内存的。
这种解释可以说明为什么在结构体内包含static变量会出错。
但是为什么C++编译器下就不会有问题呢???
解答:C++编译器将结构体视为一种特殊的class,所以不会有问题。众所周知,类体内可以包含static变量。
但是class的定义不会引起内存分配,只有当定义一个class的对象时,系统才会分配存储区。这样说的话,不分配内存空间的class中包含需要分配内存空间的static变量不就变的很奇怪了吗?
本问题暂时未找到合理的解答,期待找到高手帮我搞清概念~~