C++沉思录

第五章 代理类 :

为了实现容器或数组的多态性。

 1 #include <iostream>
2
3 using namespace std;
4
5 class Vehicle
6 {
7 public:
8 virtual void start() const = 0 ;
9 virtual Vehicle* copy() const = 0 ;
10 virtual ~Vehicle() {};
11 };
12
13
14 class AutoVehicle : public Vehicle
15 {
16 public:
17 void start() const
18 {
19 cout << "start " << endl;
20 }
21 Vehicle* copy() const
22 {
23 return new AutoVehicle(* this );
24 }
25 ~AutoVehicle(){}
26 };
27
28 class Car : public AutoVehicle
29 {
30 public:
31 void start() const
32 {
33 cout << " car start " << endl;
34 }
35 Vehicle* copy() const
36 {
37 return new Car( *this );
38 }
39 ~Car(){}
40 };
41
42 class Truck : public AutoVehicle
43 {
44 public:
45 void start() const
46 {
47 cout << " truck start " << endl;
48 }
49 Vehicle* copy() const
50 {
51 return new Truck( *this );
52 }
53 ~Truck(){};
54 };
 1 #include "vehicle.h"
2
3 class VehicleSurrogate
4 {
5 public :
6 VehicleSurrogate();
7 VehicleSurrogate( const Vehicle&);
8 VehicleSurrogate( const VehicleSurrogate&);
9 VehicleSurrogate& operator= ( const VehicleSurrogate&);
10 ~VehicleSurrogate();
11 void start();
12 private:
13 Vehicle* vp;
14 };
15 VehicleSurrogate::VehicleSurrogate() : vp ( NULL){}
16 VehicleSurrogate::VehicleSurrogate(const Vehicle& v)
17 {
18 vp = v.copy();
19 }
20 VehicleSurrogate::VehicleSurrogate(const VehicleSurrogate& v) : vp(v.vp ? v.vp->copy() : NULL) {};
21 VehicleSurrogate& VehicleSurrogate::operator=( const VehicleSurrogate& v)
22 {
23 if ( this != &v )
24 {
25 delete vp;
26 vp = (v.vp ? v.vp->copy() : NULL);
27 }
28 return *this;
29 }
30 void VehicleSurrogate::start()
31 {
32 if ( vp == NULL )
33 throw "empty";
34
35 vp->start();
36 }
37 VehicleSurrogate::~VehicleSurrogate()
38 {
39 delete vp;
40 }
 1 #include "VehicleSurrogate.h"
2
3 int main()
4 {
5
6 VehicleSurrogate parking_lot[100];
7 Car x;
8 Truck t;
9 parking_lot[0] = VehicleSurrogate( x);
10 parking_lot[1] = VehicleSurrogate( t);
11 parking_lot[0].start();
12 parking_lot[1].start();
13
14 return 0 ;
15 }





posted on 2011-12-28 00:36 lzhenf 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lzhenf/archive/2011/12/28/2304191.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值