//13.7.1 对像指针问题(Object Pointer Problem)
//13.7.2 对像指针的外套(The Coat of Object Pointer)
//Sony Handle的应用
/*#include "createsony.h" #include "sonyhandle.h" #include <iostream> enum{PUREFLAT, PLASMA, LIQUIDCRYSTAL, NANOMETER}; void fsh(SonyHandle& sh) { sh->adjustVolume(); sh->switchChannel(); } void createSonyObject(CreateSony* sp) { SonyHandle sh29(createSonyInch29(sp)); SonyHandle sh34(createSonyInch34(sp)); fsh(sh29); fsh(sh34); } int main() { if(CreateSony* sp = createCreateSony(PLASMA)){ createSonyObject(sp); delete sp; } system("pause"); return 0; }*/ #include "createsony.h" #include "sonyhandle2.h" #include <iostream> enum{PUREFLAT, PLASMA, LIQUIDCRYSTAL, NANOMETER}; void fsh(SonyHandle2& sh) { sh->adjustVolume(); sh->switchChannel(); } void createSonyObject(CreateSony* sp) { SonyHandle2 sh29(createSonyInch29(sp)); SonyHandle2 sh34(createSonyInch34(sp)); fsh(sh29); fsh(sh34); } int main() { if(CreateSony* sp = createCreateSony(NANOMETER)){ createSonyObject(sp); delete sp; } system("pause"); return 0; }
#ifndef HEADER_SONYHANDLE #define HEADER_SONYHANDLE #include "sony2.h" class SonyHandle { Sony* sp; public: Sony* operator->(){ return sp;} SonyHandle(Sony* pp) : sp(pp){}; ~SonyHandle(){} }; #endif;
#ifndef HEADER_SONYHANDLE2 #define HEADER_SONYHANDLE2 #include "sony2.h" class SonyHandle2 { Sony* sp; //定义一个Sony的指针 int* count;//定义一个整形变量 public: SonyHandle2(Sony* pp) : sp(pp),count(new int(1)){}; SonyHandle2(const SonyHandle2& sh):sp(sh.sp),count(sh.count){ (*count)++; } Sony* operator->(){ return sp;} SonyHandle2& operator+(const SonyHandle2& sh){ if(sh.sp == sp) return *this; //本来就指向同一个对像的情况 (*this).~SonyHandle2(); sp = sh.sp; count = sh.count; (*count) ++; return *this; } //SonyHandle(Sony* pp) : sp(pp){}; ~SonyHandle2(){ if(--(*count)==0) { delete sp; delete count; } } }; #endif;