首页 > 其他 > 详细

类模版的static成员

时间:2015-03-23 23:42:36      阅读:296      评论:0      收藏:0      [点我收藏+]

类模版中声明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

 

类模版的static成员

原文:http://www.cnblogs.com/kaituorensheng/p/4361029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!