往往由于需要在一个类中会添加入静态变量,这个或这些变量
可能为结构体,也可能为简单的数据类型
这样的静态变量并非属于单个类的对象,而是属于整个类
即使在对象销毁后仍然存在。
下面用代码说明问题
- #include "stdafx.h"
-
- class tt
- {
- public:
- int x;
- int y;
- char ch;
- };
- class test
- {
- public:
- int i;
- static tt t;
- };
- tt test::t = {1,2,'a'}; // 这样是正确的
- // tt test::t.x = 1; // 而像下面三个写法都是错误的,
- // tt test::t.y = 2;
- // tt test::t.ch = 'a';
- void main()
- {
- test _test;
- _test.i = 0;
- printf("%d/n", _test.i);
- // printf("%d/n", _test.t.x); // 实验证明这样的写法也是可以的
- printf("%c/n", test::t.ch);// 当然这样的写法是最适于理解的。
- }
据说类的静态成员变量都需要初始化
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。