类模版的static成员

类模版中声明static成员

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()。

类模版static成员变量的初始化

template<class T> size_t Foo<T>::ctr = 0;    //类外

类模版Foo每次实例化表示不同的类型,相同类型的对象共享一个static成员。因此下面f1、f2、f3共享一个static成员,f4、f5共享一个static成员

Foo<int> f1, f2, f3;
Foo<string> f4, f5;

访问static成员

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();
}

运行结果

1
2
3
1
2
3
原文地址:https://www.cnblogs.com/kaituorensheng/p/4361029.html