C++代理类学习

class Vehicle
{
public:
    virtual double Weight() const = 0;
    virtual void Start()  = 0;
    
    //【3】
    //存储就肯定得有复制,但是我们不知道派生类的类型,我们无法自己进行复制
    //一个比较好的方法就是用多态的机制,让派生类自己进行复制,然后通过返回值的形式进行传递
    //我们叫虚复制函数
    virtual Vehicle* copy() const = 0;

    // ...
};

class RoadVehicle: public Vehicle
{
public:
    double Weight() const { return 1.0; }
    void Start() {}

    //【4】
    //定义RoadVehicle类的copy函数
    Vehicle* copy() const
    {
        return new RoadVehicle(*this);
    }

    /*
    ...
    */
};

class Automobile: public Vehicle
{
public:
    double Weight() const { return 1.0; }
    void Start() {}

    //【5】
    //定义Automobile类的copy函数
    Vehicle* copy() const
    {
        return new Automobile(*this);
    }

    /*
    ...
    */
};


//【2】
//我们可以通过定义一个新的类,叫做Vehicle的代理类,来执行【1】中的情况
//代理类有能力让Vehicle的派生类存放在同一个容器中,而不必知道派生类的类型
class VehicleSurrogate
{
public:
    //【7】
    //构造函数和赋值操作符的定义
    VehicleSurrogate():_v(0) {}
    VehicleSurrogate(const Vehicle& v):_v(v.copy()) {}
    ~VehicleSurrogate() { delete _v; }
    VehicleSurrogate(const VehicleSurrogate& v):_v(v._v ? v._v->copy() : 0) {}
    VehicleSurrogate& operator=(const VehicleSurrogate& v)
    {
        if(this != &v)
        {
            delete _v;
            _v = (v._v ? v._v->copy() : 0);
        }
        return *this;
    }

    //【8】
    //定义所代理的对象的操作
    double Weight() const
    {
        if(_v != 0)
            return _v->Weight();
    }
    void Start()
    {
     if(_v != 0)   _v
->Start(); } private: //【6】 //一个代理类,当然包含所代理对象的内容 Vehicle* _v; }; int main() { //【1】 /*想定义一个Vehicle数组,保存各种交通工具的停车情况*/ Vehicle parking_lot[1024]; //上面的语句通不过编译,提示是:cannot instantiate abstract class //那是因为Vehicle有两个纯虚函数,不能过实例化 //【9】 //现在可以用代理类来存放Vehicle的派生类了 VehicleSurrogate parking_lot1[1024]; Automobile x; parking_lot1[0] = x; return 0; }
原文地址:https://www.cnblogs.com/littlethank/p/2598796.html