類模版中聲明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