关于struct中的static变量

先来看一段程序:

#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变量不就变的很奇怪了吗?

 

本问题暂时未找到合理的解答,期待找到高手帮我搞清概念~~

 

 

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值