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