这个代码展示了private继承和模版的一个妙用:
1 #include <iostream> 2 #include <memory> 3 4 template<typename T> 5 class Counter { 6 public: 7 Counter() { count++; } 8 Counter(const Counter&) { count++; } 9 ~Counter() { --count; } 10 public: 11 std::size_t howMany(void) { return count; } 12 private: 13 static std::size_t count; 14 }; 15 16 template<typename T> 17 std::size_t Counter<T>::count = 0; 18 19 class B : private Counter<B> { 20 public: 21 B() { } 22 ~B() { } 23 using Counter<B>::howMany; 24 private: 25 int val; 26 }; 27 28 int main(void) 29 { 30 std::auto_ptr<int> pInt(new int(5)); 31 32 std::cout << *pInt << std::endl; 33 B b1; 34 { 35 B b2; 36 std::cout << b1.howMany() << " " << b2.howMany() << std::endl; 37 } 38 39 std::cout << b1.howMany() << std::endl; 40 41 return 0; 42 }