首先static变量只有一次初始化,不管在类中还是在函数中..有这样一个函数:
- void Foo()
- {
- static int a=3; // initialize
- std::cout << a;
- a++;
- }
这里的static int a=3只执行了一次。在main中调用Foo()两次,结果为34.将上面的函数改为
- void Foo()
- {
- static int a;
- a=3; // not initialize
- std::cout << a;
- a++;
- }
同样在Foo()中调用两次.结果为33
在类中使用非const的static类成员变量。初始化时要使用typename classname::variablename = value的形式
例如:
- class myClass
- {
- public:
- static int a;
- myClass()
- {
- }
- };
- int myClass::a = 3; // here initialize
- int main()
- {
- cout << myClass::a;
- return 0;
- }
如果使用的是const类型的static变量,那么就要在类中初始化:
- class myClass
- {
- public:
- const static int a=3; // here initialize
- myClass()
- {
- }
- };
如果是模板中使用非const的static的变量..那需要根据具体类型初始化。
例如 int myClass<int>::a = 4;那么如果你调用的是cout << myClass<double>::a,那一定会编译出错的。
因为模板是不是具体类型,myClass<int>, myClass<double>才是一个具体类型,而一个类静态成员在特定类中被初始化一次。这样就好理解了。
本文详细解析了C++中static变量的初始化与使用方式,包括函数内的static变量和类中的static成员变量的区别,并介绍了const static变量的初始化方法。
1803

被折叠的 条评论
为什么被折叠?



