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 阅读(...) 评论(...) 编辑 收藏