现在的位置: 首页 > 综合 > 正文

统计产生的对象个数

2012年06月28日 ⁄ 综合 ⁄ 共 814字 ⁄ 字号 评论关闭
// templatetest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <typeinfo>
#include <string>

using namespace std;

template <typename CountedType>
class ObjectCounter{
private:
    static size_t count;
protected:
    //缺省构造函数
    ObjectCounter(){
        ++ObjectCounter<CountedType>::count;
    }

    //拷贝构造函数
    ObjectCounter(ObjectCounter const &){
        ++ObjectCounter<CountedType>::count;
    }

    //析构函数
    ~ObjectCounter(){
        --ObjectCounter<CountedType>::count;
    };

public:
    //返回存在对象的个数
    static size_t live(){
        return ObjectCounter<CountedType>::count;
    }
};

template<typename CountedType>
size_t ObjectCounter<CountedType>::count=0;

template <typename T>
class countt:public ObjectCounter<countt<T>>
{
public:
    countt()
    {}

};

int _tmain(int argc, _TCHAR* argv[])
{
    countt<int> tt;

    cout<<tt.live()<<endl;
    getchar();
    return 0;
}

抱歉!评论已关闭.