您的位置:首页 > 编程语言 > C语言/C++

C++沉思录读书笔记(5章)-代理类

2011-10-26 10:43 597 查看
问题描述:如何设计一个容器,能使得它能包含类型不同但是彼此相关的对象?

问题描述:如何复制编译时类型未知的对象?

解决方案一:使用容器存储指向对象的指针,通过继承来处理类型不同的对象。

这个方案有严重的问题:

问题一:无法让容器中的指针指向一个局部变量,例如:

Vehicle * parking_lot[1000];
Automobile x = /*..*/
Parking_lot[num_vehicles++] = &x;


一旦x不存在了,Parking_lot就不知道指向哪里了。
我们可以变通一下,让放入Parking_lot的值,指向原来对象的副本,而不直接存放原来对象的地址,例如:
Parking_lot[num_vehicles++]= new Automobile(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); }
/**/
};

假如我们想让parking_lot[p]指向的Vehicle的类型和值与parking_lot[q]指向的对象相同,可以简单是使用如下代码:parking_lot[p]
=parking_lot[q].copy();

解决方案三(与方案二作用类似,但实现手段有不同):使用代理类

代理类:行为与原类相似,又潜在的表示了所有继承自原类的类

Vehicle类的代理类VehicleSurrogate的描述如下:

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();
};

private:
Vehicle* vp;
};

完成了这些工作后,就很容易定义我们所需要的操作了,如下:

VehicleSurrogate  parking_lot[1000];
Automobile x = /*..*/
Parking_lot[num_vehicles++] = x;
//Parking_lot[num_vehicles++] = VehicleSurrogate(x);//此语句与上条语句作用一致
/*...*/
Parking_lot[p] = Parking_lot[q];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: