C++沉思录读书笔记(5章)-代理类
2011-10-26 10:43
597 查看
问题描述:如何设计一个容器,能使得它能包含类型不同但是彼此相关的对象?
问题描述:如何复制编译时类型未知的对象?
解决方案一:使用容器存储指向对象的指针,通过继承来处理类型不同的对象。
这个方案有严重的问题:
问题一:无法让容器中的指针指向一个局部变量,例如:
一旦x不存在了,Parking_lot就不知道指向哪里了。
我们可以变通一下,让放入Parking_lot的值,指向原来对象的副本,而不直接存放原来对象的地址,例如:
Parking_lot[num_vehicles++]= new Automobile(x);
这个改进方案又带来一个问题,那就是我们必须知道x的静态类型。假如我们想让parking_lot[p]指向的Vehicle的类型和值与parking_lot[q]指向的对象相同,那在我们无法得知parking_lot[q]的静态类型的情况下,我们无法做到这点。
解决方案二(方案一的改进):增加虚拟复制函数来复制编译时类型未知的对象,代码描述如下
假如我们想让parking_lot[p]指向的Vehicle的类型和值与parking_lot[q]指向的对象相同,可以简单是使用如下代码:parking_lot[p]
=parking_lot[q].copy();
解决方案三(与方案二作用类似,但实现手段有不同):使用代理类
代理类:行为与原类相似,又潜在的表示了所有继承自原类的类
Vehicle类的代理类VehicleSurrogate的描述如下:
完成了这些工作后,就很容易定义我们所需要的操作了,如下:
问题描述:如何复制编译时类型未知的对象?
解决方案一:使用容器存储指向对象的指针,通过继承来处理类型不同的对象。
这个方案有严重的问题:
问题一:无法让容器中的指针指向一个局部变量,例如:
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];
相关文章推荐
- c++沉思录读书笔记(一)代理类
- C++沉思录读书笔记(一)代理类
- C++ primer plus 第五版 学习笔记 5章7题
- vs2005 引用webservice后自动生成的代理类在哪里?
- 通过代理类调用webservice
- WCF:如何创建带有异步访问委托的代理类
- WCF服务编程设计规范(8):服务托管、自托管代码、客户端代理类、客户端代理管理、客户端异常管理、数据契约、SOAP与REST
- 使用 gsoap 产生 webservice 代理类
- C++沉思录读书笔记(二)
- C++沉思录读书笔记(8章)-一个面向对象程序范例2
- Java代理类Proxy
- 代理类的理解
- vs中添加wsdl生成代理类工具
- C++沉思录读书笔记
- 利用VS的命令提示生成代理类
- JavaScript笔记(前5章)
- android中的重要java知识点回顾2(内省、注解、泛型、代理类、动态类、AOP框架等等)
- JDK Proxy 代理类是如何生成的?
- WCF 服务IIS部署 SvcUtil.exe 工具文件地址 及 生成代理类命令
- 分析代理类的作用与原理及AOP概念