class Vehicle{ public: virtual double weight() const = 0; virtual void start() = 0; // ... }; class RoadVehicle : public Vehicle{ / * ... */ }; class AutoVehicle : public RoadVehicle{ /* ... */}; class Aircraft : public Vehicle { / * ... */}; class Helicopter : public Aircraft { / * ... */};
Vehicle parking_lot[1000];
AutoVehicle x= /* ... */ Parking_lot[num_vehicles++] = x;
Vehicle * Parking_lot[1000]; // 指针数组
AutoVehicle x = /* ... */ Parking_lot[ num_vehicles++ ] = &x;
一旦x不存在了,Parking_lot就不知道指向哪里了。
我们可以变通一下,让放入Parking_lot的值,指向原来对象的副本,而不直接存放原来对象的地址,例如:
Parking_lot[num_vehicles++]= new AutoVehicle(x);
这个改进方案又带来一个问题,那就是我们必须知道x的静态类型。假如我们想让parking_lot[p]指向的Vehicle的类型和值与parking_lot[q]指向的对象相同,那在我们无法得知parking_lot[q]的静态类型的情况下,我们无法做到这点。
class Vehicle { public: virtual Vehicle * copy() const = 0; /**/ };//Vehicle的派生类都自实现copy函数 class Truck : public RoadVehicle { public: Vehicle* copy() const { return new Truck(*this); } /**/ }; //同时也该增加一个析构函数: class Vehicle{ public: virtual double weight() const = 0; virtual void start() = 0; virtual Vehicle * copy() const = 0; virtual ~Vehicle() {} // ... };
class VehicleSurrogate { public: VehicleSurrogate() : vp(NULL) {}; VehicleSurrogate(const Vehicle& v) : vp(v.copy()) {}; ~VehicleSurrogate() {}; VehicleSurrogate(const VehicleSurrogate& v) : vp(v.vp ? v.vp->copy() : NULL) {}; //v.vp非零检测 VehicleSurrogate& operator=(const VehicleSurrogate& v) { if (this != &v) // 确保没有将代理赋值给它自身 { delete vp; vp = (v.vp ? v.vp->copy() : NULL); } return *this; }; //来自类Vehicle的操作 void start() { if (vp == 0) throw "empty VehicleSurrogate.start()"; vp->start(); }; double weight() const { if(vp == 0) throw "empty VehcileSurrogate.weight()"; return vp->weight(); } private: Vehicle* vp; };
VehcileSurrogate parking_lot[ 1000 ] AutoVehicle x; parking_lot[ num_vehicles++] = x;
parking_lot[ num_vehicles++ ] = VehicleSurrogate(x);