zoukankan      html  css  js  c++  java
  • 类模版的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
    
  • 相关阅读:
    BZOJ-1497 最大获利
    POJ-3680 Intervals & NOI 2008 志愿者招募 费用流
    CodeForces 663E Binary Table
    南昌区域赛-G Eating Plan
    HDU-5909 Tree Cutting
    BZOJ-4589 Hard Nim
    UVA-12633 Super Rooks on Chessboard
    SPOJ-TSUM Triple Sums
    HDU-4609 3-idiots
    Kattis-aplusb A+B problem
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/4361029.html
Copyright © 2011-2022 走看看