加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++类模板中的静态成员

发布时间:2020-12-16 07:41:28 所属栏目:百科 来源:网络整理
导读:类模板中可以定义静态成员,从该类模板实例化得到的所有类都包含同样的静态成员。 程序示例如下: #include iostreamusing namespace std;template class Tclass A{private: static int count;public: A() { count ++; } ~A() { count -- ; }; A(A ) { count
类模板中可以定义静态成员,从该类模板实例化得到的所有类都包含同样的静态成员。

程序示例如下:
#include <iostream>
using namespace std;
template <class T>
class A
{
private:
    static int count;
public:
    A() { count ++; }
    ~A() { count -- ; };
    A(A &) { count ++ ; }
    static void PrintCount() { cout << count << endl; }
};
template<> int A<int>::count = 0;
template<> int A<double>::count = 0;
int main()
{
    A<int> ia;
    A<double> da;
    ia.PrintCount();
    da.PrintCount();
    return 0;
}
程序的输出结果是:
1
1

第 14 行和第 15 行,对静态成员变量在类外部加以声明是必需的。在 Visual Studio 2008 中,这两行也可以简单地写成:

int A<int>::count = 0;
int A<double>::count = 0;

A<int> 和 A<double> 是两个不同的类。虽然它们都有静态成员变量 count,但是显然,A<int> 的对象 ia 和 A<double> 的对象 da 不会共享一份 count。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读