目标:设计一个C++容器类,使它有能力包含类型不同而彼此相关的对象
思考:容器通常只能包含一种类型的对象,所以很难再容器中存储对象本身。存储指向对象的指针的话,增加了内存分配的额外负担
方法:定义名为代理(surrogate)的对象来解决该问题。代理运行起来和它所代表的对象基本相同,但是运行将整个派生层次压缩在一个对象类型中。
其实就是将指针对象化 ------ 这个想法很实用。
#include <iostream>
using namespace std;
class Vehicle{
public:
virtual int get_weight() const = 0;
virtual void start() = 0;
virtual Vehicle* copy() const = 0;
virtual ~Vehicle() {}
//...
};
class RoadVehicle: public Vehicle {
public:
RoadVehicle(): weight(10) {}
int get_weight() const { return weight; }
void start() { cout << "RoadVehicle start" << endl; }
Vehicle* copy() const { return new RoadVehicle(*this); }
private:
int weight;
};
class AutoVehicle: public RoadVehicle {
public:
AutoVehicle(): weight(10) {}
int get_weight() const { return weight; }
void start() { cout << "AutoVehicle start" << endl; }
Vehicle* copy() const { return new AutoVehicle(*this); }
private:
int weight;
};
class Trunk: public AutoVehicle {
public:
Trunk(): weight(20) {}
int get_weight() const { return weight; }
void start() { cout << "Trunk start" << endl; }
Vehicle* copy() const { return new Trunk(*this); }
private:
int weight;
};
class Aircraft: public Vehicle {
public:
Aircraft(): weight(100) {}
int get_weight() const { return weight; }
void start() { cout << "Aircraft start" << endl; }
Vehicle* copy() const { return new Aircraft(*this); }
private:
int weight;
};
class Helicopter: public Aircraft {
public:
Helicopter(): weight(50) {}
int get_weight() const { return weight; }
void start() { cout << "Helicopter start" << endl; }
Vehicle* copy() const { return new Helicopter(*this); }
private:
int weight;
};
class VehicleSurrogate
{
private:
Vehicle *vp;
public:
VehicleSurrogate(): vp(0) {}
VehicleSurrogate(const Vehicle& v): vp(v.copy()) {}
~VehicleSurrogate() { delete vp; }
VehicleSurrogate(const VehicleSurrogate& v)
{
vp = (v.vp ? v.vp->copy() : 0);
}
VehicleSurrogate& operator=(const VehicleSurrogate& v)
{
if(this != &v){
delete vp;
vp = (v.vp ? v.vp->copy() : 0);
}
return *this;
}
void start()
{
if(vp == NULL)
throw "empty VehicleSurrogate.start()";
return vp->start();
}
int get_weight() const
{
if(vp == NULL)
throw "empty VehicleSurrogate.get_weight()";
return vp->get_weight();
}
};
int main(int argc, char const *argv[])
{
VehicleSurrogate parking_lot[1000];
Trunk x;
parking_lot[0] = x;
parking_lot[0].start();
cout<< parking_lot[0].get_weight() << endl;
return 0;
}
我写完这段代码,运行之后,结果让我惊诧。C++竟然这么好用。
真的是写好了类,用起来方便极了。
原文:https://www.cnblogs.com/vonyoven/p/11777159.html