C++ 代理类的实现

来源:互联网 发布:使命召唤10 知乎 编辑:程序博客网 时间:2024/06/05 21:03
#include <string>#include <iostream>class Vehicle{protected:    std::string name;public:    Vehicle():name("noName"){};    Vehicle(const std::string& s):name(s){};    virtual Vehicle * clone() const = 0;    virtual void run() const = 0;    virtual ~Vehicle(){std::cout <<" Base destruction!" << std::endl;}};class Car :public Vehicle{public:    Car():Vehicle("car"){};    Car(const std::string & s):Vehicle(s){};    void run() const{std::cout << name << " is running" << std::endl;}    Car * clone()const {return new Car("car");}    ~Car(){std::cout <<" Car destruction!" << std::endl;}};class Truck: public Vehicle{public:    Truck():Vehicle("truck"){};    Truck(const std::string & s):Vehicle(s){};    void run() const{std::cout << name << " is running" << std::endl;}    Truck * clone()const {return new Truck("truck");}    ~Truck(){std::cout <<" Truck destruction!" << std::endl;}};class AirPlane:public Vehicle{public:    AirPlane():Vehicle("airPlane"){};    AirPlane(const std::string & s):Vehicle(s){};    void run() const{std::cout << name << " is running" << std::endl;}    AirPlane * clone()const {return new AirPlane("airplane");}    ~AirPlane(){std::cout <<" AirPlane destruction!" << std::endl;}};class VehicleProxy{private:    Vehicle *ve;public:    VehicleProxy():ve(0){}    VehicleProxy(const Vehicle & v):ve(v.clone()){}    VehicleProxy(const VehicleProxy &vs):ve(vs.ve ? vs.ve->clone() : 0){}    VehicleProxy & operator = (const VehicleProxy & vs);    ~VehicleProxy(){delete ve;}    void run(){if(ve != 0) ve->run();}};VehicleProxy & VehicleProxy::operator = (const VehicleProxy & vs){    if(&vs != this)    {        delete ve;        ve = vs.ve->clone();    }    return *this;}int main(){VehicleProxy vehicleProxy[3];    Car car;    Truck truck;    AirPlane airPlane;    vehicleProxy[0] = car;    vehicleProxy[1] = truck;    vehicleProxy[2] = airPlane;    for(int i = 0; i < 3; i++)        vehicleProxy[i].run();    return 0;}

0 0