http://hi.baidu.com/cndx100/blog/item/e009cd46e3a9650f6a63e5e4.html
http://hi.baidu.com/gylxue/blog/item/598d62fa0f1064d5b48f318d.html
#include "stdafx.h" #include <iostream> using namespace std; //表示交通工具的派生类 class Vehicle { public: virtual double weight() const = 0; virtual void start() = 0; virtual Vehicle* copy() const = 0; }; class RoadVehicle : public Vehicle { public: double weight() const { return 1.0; } void start() { cout<<"run"<<endl; } Vehicle* copy() const { return new RoadVehicle(*this); } }; class AutoVehicle : public Vehicle { public: double weight() const { return 2.0; } void start() { cout<<"run"<<endl; } Vehicle* copy() const { return new AutoVehicle(*this); } }; class Aircraft : public Vehicle { public: double weight() const { return 3.0; } void start() { cout<<"fly"<<endl; } Vehicle* copy() const { return new Aircraft(*this); } }; class Helicopter : public Vehicle { public: double weight() const { return 4.0; } void start() { cout<<"fly"<<endl; } Vehicle* copy() const { return new Helicopter(*this); } }; //代理类 class VehicleSurrogate { public: VehicleSurrogate() : vp(0) {} VehicleSurrogate(const Vehicle& other) : vp(other.copy()) {} VehicleSurrogate(const VehicleSurrogate& other) { vp = (other.vp ? other.vp->copy() : 0); } VehicleSurrogate& operator= (const VehicleSurrogate& other) { if (this != &other) { delete vp; vp = (other.vp ? other.vp->copy() : 0); } return *this; } ~VehicleSurrogate() { delete vp; } //来自Vehicle类的函数 double weight() const { if(vp == NULL) throw "empty VehicleSurrogate.weight()"; return vp->weight(); } void start() { if(vp == NULL) throw "empty VehicleSurrogate.start()"; vp->start(); } Vehicle* copy() const { return vp->copy(); } private: Vehicle *vp; }; int main() { VehicleSurrogate arr[1000]; //这样数组arr就可以存放Vehicle继承体系的任何元素Vehicle AutoVehicle x; arr[0] = x;//该句等价于下句 arr[0] = VehicleSurrogate(x); }