类模版中声明static成员css
template <class T> class Foo { public: static size_t count() { ++ctr; cout << ctr << endl; return ctr; } private: static size_t ctr; };
类模版Foo中static的成员变量ctr和成员函数count()。ios
类模版static成员变量的初始化函数
template<class T> size_t Foo<T>::ctr = 0; //类外
类模版Foo每次实例化表示不一样的类型,相同类型的对象共享一个static成员。所以下面f一、f二、f3共享一个static成员,f四、f5共享一个static成员spa
Foo<int> f1, f2, f3; Foo<string> f4, f5;
访问static成员code
f4.count(); //经过对象访问 f5.count(); Foo<string>::count(); //经过类做用操做符直接访问
完整代码对象
#include <iostream> using namespace std; template <class T> class Foo { public: static size_t count() { ++ctr; cout << ctr << endl; return ctr; } private: static size_t ctr; }; template<class T> size_t Foo<T>::ctr = 0; int main() { Foo<int> f1, f2, f3; f1.count(); f2.count(); f3.count(); Foo<string> f4, f5; f4.count(); f5.count(); Foo<string>::count(); }
运行结果blog
1 2 3 1 2 3