转载:http://blog.csdn.net/ljq32/article/details/7911390
1. 与普通类的static成员一样,类内部声明一次,类外部定义一次,定义时可以设置也可以不设置初始值;
2. 类模板内部声明与普通类的static成员一致:
- //16.4.7.h
- template <class T>
- class Foo
- {
- public:
- static int count() { return cnt; }
-
- private:
- static int cnt; //类模板内部声明静态变量cnt
- //也必须在类模板外部定义一次cnt,否则编译错误:"undefined reference to `Foo<int>::cnt'";
- };
3. 类模板外部定义一次,通常在类模板定义文件中,定义时不带关键字static,必须以模板形参表与模板名字进行限定,以指出它是类模板的成员;
- //16.4.7.cpp
- #include <iostream>
- #include "16.4.7.h"
- using namespace std;
-
- //类模板定义文件定义cnt并给定初始值,当未明确指定初始值时,默认值为相应数据类型的默认值,int类型为0;
- template <class T> int Foo<T>::cnt = -1;
-
- int main()
- {
- //static成员cnt的不同使用方式
- Foo<int> f;
- Foo<int> *pf = &f;
- Foo<int> &rf = f;
- cout << "f.count():" << f.count() << endl;
- cout << "rf.count():" << rf.count() << endl;
- cout << "pf->count():" << pf->count() << endl;
- cout << "Foo<int>::count():" << Foo<int>::count() << endl;
-
- return 0;
- }
-
- 运行结果:
- f.count():-1
- rf.count():-1
- pf->count():-1
- Foo<int>::count():-1
-