刚刚看完"C++沉思录" "Ruminations on C++"第5章,按照代理的思想,把代码放在这儿,以便以后查看 /** * @file surrogate.cpp * @brief * @author liugang * @version 1.0 * @date 2009-11-29 */ #include <iostream> using namespace std; ////////////////////////////////////////////////////////// // Base class class Vehicle{ public: virtual double weight() const = 0; virtual void start() = 0; virtual Vehicle* copy() const = 0; virtual ~Vehicle() {} }; ////////////////////////////////////////////////////////// // Surrogate class class VehicleSurrogate: public Vehicle{ public: VehicleSurrogate(); VehicleSurrogate(const Vehicle&); ~VehicleSurrogate(); VehicleSurrogate(const VehicleSurrogate&); VehicleSurrogate& operator=(const VehicleSurrogate&); // implement Vehicle double weight() const; void start(); Vehicle* copy() const { return new VehicleSurrogate(*this);} private: Vehicle* vp; }; VehicleSurrogate::VehicleSurrogate(): vp(0) { } VehicleSurrogate::VehicleSurrogate(const Vehicle& v): vp(v.copy()) { } VehicleSurrogate::~VehicleSurrogate() { delete vp; } VehicleSurrogate::VehicleSurrogate( const VehicleSurrogate& v): vp(v.vp? v.vp->copy(): 0) { } VehicleSurrogate& VehicleSurrogate::operator=(const VehicleSurrogate& v) { if(this != &v){ delete vp; vp = (v.vp ? v.vp->copy() : 0); } return *this; } double VehicleSurrogate::weight() const { if (vp == 0) throw "empty VehicleSurrogate.weight()"; return vp->weight(); } void VehicleSurrogate::start() { if (vp == 0) throw "empty VehicleSurrogate.start()"; vp->start(); } ////////////////////////////////////////////////////////// // class Automobile class Automobile:public Vehicle{ public: // Automobile(){}; // Automobile(double weight){ fWeight = weight;} // Automobile(double weight):fWeight(weight){} // Automobile(double weight = 6.0):fWeight(weight){} // ~Automobile(){} // here it isn't necessary, because there is no dynamic memory to free; // double weight() const { return fWeight; } double weight() const { return 6.0; } void start() { cout << "start..." << endl; } Vehicle* copy() const { return new Automobile(*this);} private: // double fWeight; }; ////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { int num_vehicles = 0; VehicleSurrogate parking_lot[1000]; Automobile x; parking_lot[num_vehicles++] = x; // parking_lot[num_vehicles++] = VehicleSurrogate(x); return 0; } /* vim: set ts=8 sw=8: */