c++沉思录 学习笔记 第五章 代理类

时间:2023-03-08 22:54:39
c++沉思录 学习笔记 第五章 代理类

Vehicle 一个车辆的虚基类

class Vehicle {
public:
virtual double weight()const = 0;
virtual void start() = 0;
virtual Vehicle* copy() = 0;
virtual ~Vehicle() {};
};

衍生出RoadVehicle AutoVehicle两个类

如果有一个停车场类 可以容纳100辆车

一开始计划 有Vehicle[100]这种变量来表示停车场

但是Vehicle是虚基类 不能有实例化的实体 也就不会有数组

所以需要一个代理类来保存Vehicle的指针 它可以指向任意的Vehicle的衍生类

同时考虑到拷贝操作 添加了拷贝函数

class VehicelSurrogate {
public:
VehicelSurrogate() :vp(0) {};
VehicelSurrogate( Vehicle& v) :vp(v.copy()) {};
VehicelSurrogate(const VehicelSurrogate& v):vp(v.vp ? v.vp->copy() : 0) {};
~VehicelSurrogate() {
delete vp;
};
VehicelSurrogate& operator=(const VehicelSurrogate& v) {
if (this != &v) {
delete vp;
vp = (v.vp ? v.vp->copy() : 0);
}
return *this;
};
double weight() {
return vp->weight();
}

private:
Vehicle* vp;
};

如此 就可以使用VehicelSurrogate[100]来表示停车场的概念

完整代码如下

 // test5.cpp: 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <iostream> class Vehicle {
public:
virtual double weight()const = ;
virtual void start() = ;
virtual Vehicle* copy() = ;
virtual ~Vehicle() {};
}; class RoadVehicle:public Vehicle{
public:
virtual double weight() const{
return ;
}
virtual void start() {}
virtual Vehicle* copy() {
return new RoadVehicle(*this);
}
virtual ~RoadVehicle() {}
};
class AutoVehicle:public RoadVehicle{
public:
virtual double weight() const{
return ;
}
virtual void start() {}
virtual Vehicle* copy() {
return new AutoVehicle(*this);
}
virtual ~AutoVehicle() {} }; class VehicelSurrogate {
public:
VehicelSurrogate() :vp() {};
VehicelSurrogate( Vehicle& v) :vp(v.copy()) {};
VehicelSurrogate(const VehicelSurrogate& v):vp(v.vp ? v.vp->copy() : ) {};
~VehicelSurrogate() {
delete vp;
};
VehicelSurrogate& operator=(const VehicelSurrogate& v) {
if (this != &v) {
delete vp;
vp = (v.vp ? v.vp->copy() : );
}
return *this;
};
double weight() {
return vp->weight();
} private:
Vehicle* vp;
}; int main()
{
VehicelSurrogate parking_lot[];
AutoVehicle x;
parking_lot[] = x;
std::cout << parking_lot[].weight() << std::endl;;
return ;
}