(九)Vehicle
2023-03-27 本文已影响0人
GoodTekken
#include <typeinfo>
#include <iostream>
using namespace std;
class Vehicle /*抽象基类,车辆*/
{
public:
virtual void run() = 0;
};
class Emergency
{
public:
virtual bool isEmergent() = 0; //(1)
virtual void runRedLight() = 0; //(2)
};
class Car : public Vehicle
{
public:
~Car()
{
}
void run()
{
}
};
class Truck : public Vehicle
{
public:
~Truck();
void run()
{
}
};
class PoliceCar : public Car , public Emergency //(3)
{
private:
bool isEmergency;
public:
PoliceCar(): Car(),Emergency()
{
this->isEmergency = false;
}
PoliceCar(bool b) : Car(),Emergency()
{
this->isEmergency = b;
}
~PoliceCar()
{
}
bool isEmergent()
{
return isEmergency; //(4)
}
void runRedLight()
{
}
};
class Ambulance : public Car , public Emergency
{
private:
bool isEmergency;
public:
Ambulance(): Car(),Emergency()
{
this->isEmergency = false;
}
Ambulance(bool b) : Car(),Emergency()
{
this->isEmergency = b;
}
~Ambulance()
{
}
bool isEmergent()
{
return isEmergency;
}
void runRedLight()
{
}
};
class FireEngine : public Truck , public Emergency
{
private:
bool isEmergency;
public:
FireEngine(): Truck(),Emergency()
{
this->isEmergency = false;
}
FireEngine(bool b) : Truck(),Emergency()
{
this->isEmergency = b;
}
~FireEngine()
{
}
bool isEmergent()
{
return this->isEmergency;
}
void runRedLight()
{
}
};
class TraficControlSystem
{
private:
Vehicle* v[24];
int numVehicles = 0;
public:
void control()
{
for(int i = 0; i < numVehicles; i++)
{
Emergency* ev = dynamic_cast<Emergency*>(v[i]);
if(ev !=0 )
{
ev->runRedLight(); //(5)
}
else
{
v[i]->run(); //(6)
}
}
}
void add(Vehicle* vehicle)
{
v[numVehicles++] = vehicle;
}
void shutDown()
{
for( int i = 0; i < numVehicles; i++)
{
delete v[i];
}
}
};
int main()
{
TraficControlSystem* tcs = new TraficControlSystem;
tcs->add(new Car());
tcs->add(new PoliceCar);
tcs->add(new Ambulance());
tcs->add(new Ambulance(true));
tcs->add(new FireEngine(true));
delete tcs;
return 0;
}
答案:
(1)virtual bool isEmergent()
(2)virtual void runRedLight()
(3)public Car , public Emergency
(4)this->isEmergency
(5)ev
(6)v[i]