看Ruminations on C++ 的時候照著寫的,簡單的框架,留作備份吧。
// 代理類 Demo
// 將繼承和容器共用,迫使我們要處理兩個問題:
// 控制內存分配和把不同類型的對象放入同一個容器中。
// 代理類的每個對象都代表另一個對象,該對象可以是
// 位于一個完整繼承層次中的任何類的對象。通過在容器中
// 用代理對象而不是對象本身來解決以上兩個問題

#include <process.h> // system()
#include <iostream>
using namespace std;

// 所有交通工具的基類
class Vehicle


{
public:
virtual void start() = 0;
// 動態復制
virtual Vehicle* copy() const = 0;
// 虛析構函數

virtual ~Vehicle()
{}
};

// 交通工具的代理類
class VehicleSurrogate


{
public:
// 無參構造函數,用于創建數組
VehicleSurrogate();
// 用Vehicle 及其派生類構造
VehicleSurrogate(const Vehicle&);
~VehicleSurrogate();
// 拷貝及賦值
VehicleSurrogate(const VehicleSurrogate&);
VehicleSurrogate& operator=(const VehicleSurrogate&);

// Vehicle 的方法
void start();
private:
Vehicle* p;
};


VehicleSurrogate::VehicleSurrogate() : p(0)
{}


VehicleSurrogate::VehicleSurrogate(const Vehicle& v) : p(v.copy())
{}

VehicleSurrogate::VehicleSurrogate(const VehicleSurrogate& vs)

: p(vs.p ? vs.p->copy() : 0)
{}

VehicleSurrogate & VehicleSurrogate::operator =(const VehicleSurrogate& vs)


{
if (p != vs.p)

{
delete p;
p = vs.p ? vs.p->copy() : 0;
}
return *this;
}


VehicleSurrogate::~VehicleSurrogate()
{ delete p; }

void VehicleSurrogate::start()


{
if (p)
p->start();
else
cout << "Error" << endl;
}

class RoadVehicle : public Vehicle


{
public :
void start()

{
cout << "RoadVehicle start." << endl;
}
Vehicle* copy() const

{
return (Vehicle*) new RoadVehicle(*this);
}
~RoadVehicle()

{
}
};

class AutoVehicle : public RoadVehicle


{
public :
void start()

{
cout << "AutoVehicle start." << endl;
}
Vehicle* copy() const

{
return (Vehicle*) new AutoVehicle(*this);
}
~AutoVehicle()

{
}
};

void main()


{
VehicleSurrogate pa[3];
RoadVehicle* prv = new RoadVehicle();
pa[0] = *prv;
delete prv;
pa[1] = AutoVehicle();
pa[2] = RoadVehicle();
pa[0].start();
pa[1].start();
pa[2].start();
system("pause");
}






















































































































































