????????Widget?????????Counter??????????????????????????????л????????Counter??????Fish???????Counter??????Σ????????????????????????????Widget??Fish??????????????????????У??????????壡???£?
01.template
02.classCounter {
03.public:
04.Counter() { ++count; }
05.Counter(constCounter&) { ++count; }
06.~Counter() { --count; }
07.
08.staticsize_t howMany()
09.{return count; }
10.
11.private:
12.staticsize_t count;
13.};
14.
15.// this now can go in header
16.templatesize_t Counter::count = 0;
?????????????????
01.// embed a Counter to count objects
02.classWidget {
03.public:
04......
05.staticsize_t howMany()
06.{returnCounter::howMany();}
07.private:
08......
09.Counter c;
10.};
11.
12.//or:
13.
14.// inherit from Counter to count objects
15.classWidget: public Counter {
16......
17.};
??????????????????????Counter???????????????????????????
????????????????????????????????????????????????????????
?????????public??У???class Widget: public Counter??????????о?????????????????Counter???????????????麯??????????????????delete????????????δ???壨??????3???crash????????
????1.Counter *pw =new Widget; // get base class ptr to derived class object
????2.......
????3.deletepw; // yields undefined results if the base class lacks a virtual destructor
?????????Counter??????????????????????vTable???????????????????Ч????????????????????????????protected?????????????delete pw??????????±??????
????1.template
????2.classCounter {
????3.public:
????4......
????5.protected:
????6.~Counter() { --count; }
????7......
????8.};
??????Σ?Counter???????????????????????????Counter??????????????public??????????????????????????Counter?????????????????????inline?????????Counter???HowMany????????????????ε????????????????????????檔Counter????з???????????????????????Counter??????С?0??????????C++?漲???ж?????СС?????1???????????÷???????????????С????????????????????size????0??????public??з?????????????????С??
??????????????????????????????private??У???class Widget: private Counter?????????????????
????1.classWidget: private Counter {
????2.public:
????3.// make howMany public
????4.usingCounter::howMany;
????5.
????6......// rest of Widget is unchanged
????7.};
???????????????????
????1.Counter *pw =new Widget; //??м?в????????????
????????????public??з???????????????????????????Щ????????????????????????SpecialWidget????????Widget??????SpecialWidget??????????????£?
????1.classSpecialWidget: publicWidget??
????2.publicCounter {
????3.public:
????4.};
????????????SpecialWidget????????????????????Widget??????????????????Widget???????Widget??????ж???SpecialWidget??????ж????????????????????????SpecialWidget????Widget?????????????Σ???????μ?????
???????
????????????????????????????????????????????????????????м?й??????????????????????CUG??C++???Scott Meyers???????2??????????