分类: C/C++
2009-10-13 09:55:32
class Widget {
public:
Widget() { ++count; }
Widget(const Widget&) { ++count; }
~Widget() { --count; }
static size_t howMany() { return count; }
private:
static size_t count;
};
//cpp文件中
size_t Widget::count = 0;
下面我们将逐步实现并完善这个通用的计数类。
class Counter {
public:
Counter() { ++count; }
Counter(const Counter&) { ++count; }
~Counter() { --count; }
static size_t howMany() { return count; }
private:
static size_t count;
};
// This still goes in an implementation file
size_t Counter::count = 0;
//方法一: embed a Counter to count objects
class Widget {
public:
..... // all the usual public
// Widget stuff
static size_t howMany() { return Counter::howMany(); }
private:
..... // all the usual private
// Widget stuff
Counter c;
};
//or:
//方法二: inherit from Counter to count objects
class Widget: public Counter {
public:
..... // all the usual public
// Widget stuff
private:
..... // all the usual private
// Widget stuff
};
//方法一: embed a Counter to count objects
class Widget {
public:
.....
static size_t howMany() {return Counter
private:
.....
Counter
};
//or:
//方法二: inherit from Counter to count objects
class Widget: public Counter
.....
};
Counter
// get base class ptr to derived class object
......
delete pw; // yields undefined results if the base class lacks a virtual destructor
template
class Counter {
public:
.....
protected:
~Counter() { --count; }
.....
};
class Widget: private Counter
public:
// make howMany public
using Counter
..... // rest of Widget is unchanged
};
Counter
class SpecialWidget: public Widget,
public Counter
public:
};