1 #include <iostream> 2 #include <stdexcept> 3 #include <memory> 4 template <typename T> 5class tooManyPeople:public std::exception 6{ 7public: 8 TooManyPeople(std::string e) 9 :errorMsg(e) 10 {} 11 ~TooManyPeople( ) throw( ) {} 12constchar * what( ) constthrow( ); 13private: 14 std::string errorMsg; 15}; 16 17constchar* TooManyPeople::what( ) constthrow( ) 18{ 19return errorMsg.c_str( ); 20} 21 22 tempalte <typename T> 23class counted 24{ 25public: 26staticint objectCount( ) { return numObject; } 27protected: 28 counted( ); 29 counted(const Counted& rhs); 30 ~Counted( ) { --numObject; } 31private: 32staticconst std::size_t maxObject; 33staticint numObject 34void init( ); 35}; 36 37 template<typename T> int count<T>::numObject=0; 38 39 template<typename T> const std::size_t counted<T>::maxObject=2; 40 41 template<typename T> counted<T>::counted( ) 42{ 43 init( ); 44} 45 46 template<typename T> counted<T>::counted( const counted& rhs) 47{ 48 init( ); 49} 50 51 template<typename T> void counted<T>::init( ) 52{ 53if(numObject >=maxObject) 54 { 55throw tooManyObject("Error: Too Many Object!!"); 56 } 57 ++numObject; 58} 59 60class People:private Counted<People> 61{ 62public: 63static People * makePeople( ); 64static People * makePeople( const std::string n,constint a); 65static People * makePeople(const People& rhs); 66 ~People( ); 67using Counted<People>::objectCount; 68private: 69 People( ) 70 :name(""),age(0) 71 {} 72 People(const std::string n,constint a) 73 :name(n),age(a) 74 {} 75 People( const People & rhs); 76private: 77 std::string name; 78int age; 79} 80 81 People::People(const People & rhs) 82{ 83 name=rhs.name; 84 age=rhs.age; 85} 86 87 People* People::makePeople( ) 88{ 89returnnew People( ); 90} 91 92 People* People::makePeople( const std::string n,constint a) 93{ 94returnnew People(n,a); 95} 96 97 People* People::makePeople(const People & rhs) 98{ 99returnnew People(rhs);100}101102int main( int argc,char ** argv)103{104try105 {106 std::auto_ptr<People> p1(People::makePeople("tom",16));107 std::cout<<"The number of object is"<<People::counted<People>::objectCount( )<<std::endl;108 std::auto_ptr<People> p2(People::makePeople( ));109 std::cout<<"The number of object is"<<People::counted<People>::objectCount( )<<std::endl;110 std::auto_ptr<People p3(People::makePeople("sim",15));111 }112catch(std::exception &e)113 {114 std::cerr<<e.what( )<<std::endl;115 }116return0;117 }