C++ 类实现停车场管理系统:功能丰富,代码示例
下面是一个功能丰富的 C++ 停车场管理系统的示例:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 车辆类
class Vehicle {
public:
string licensePlate;
string brand;
Vehicle(string _licensePlate, string _brand)
: licensePlate(_licensePlate), brand(_brand) {}
};
// 停车位类
class ParkingSpot {
public:
int spotNumber;
bool isOccupied;
Vehicle* parkedVehicle;
ParkingSpot(int _spotNumber)
: spotNumber(_spotNumber), isOccupied(false), parkedVehicle(nullptr) {}
};
// 停车场类
class ParkingLot {
private:
int capacity;
vector<ParkingSpot> parkingSpots;
public:
ParkingLot(int _capacity)
: capacity(_capacity), parkingSpots(capacity, ParkingSpot(0)) {
for (int i = 0; i < capacity; i++) {
parkingSpots[i].spotNumber = i + 1;
}
}
// 进入停车场
void enterParkingLot(Vehicle* vehicle) {
for (auto& spot : parkingSpots) {
if (!spot.isOccupied) {
spot.isOccupied = true;
spot.parkedVehicle = vehicle;
cout << vehicle->licensePlate << ' 进入停车场,停在停车位 ' << spot.spotNumber << '。' << endl;
return;
}
}
cout << '停车场已满,无法停车。' << endl;
}
// 离开停车场
void leaveParkingLot(Vehicle* vehicle) {
for (auto& spot : parkingSpots) {
if (spot.isOccupied && spot.parkedVehicle == vehicle) {
spot.isOccupied = false;
spot.parkedVehicle = nullptr;
cout << vehicle->licensePlate << ' 离开停车场。' << endl;
return;
}
}
cout << '未找到车辆 ' << vehicle->licensePlate << ',无法离开停车场。' << endl;
}
// 显示当前停车场的车辆信息
void displayParkingLot() {
cout << '当前停车场车辆信息:' << endl;
for (const auto& spot : parkingSpots) {
if (spot.isOccupied) {
cout << '停车位 ' << spot.spotNumber << ':车牌号:' << spot.parkedVehicle->licensePlate
<< ',品牌:' << spot.parkedVehicle->brand << endl;
} else {
cout << '停车位 ' << spot.spotNumber << ':空闲' << endl;
}
}
}
};
int main() {
ParkingLot parkingLot(5);
// 进入停车场
Vehicle vehicle1('粤A12345', '奥迪');
parkingLot.enterParkingLot(&vehicle1);
Vehicle vehicle2('粤B67890', '宝马');
parkingLot.enterParkingLot(&vehicle2);
Vehicle vehicle3('粤C24680', '奔驰');
parkingLot.enterParkingLot(&vehicle3);
// 显示当前停车场的车辆信息
parkingLot.displayParkingLot();
// 离开停车场
parkingLot.leaveParkingLot(&vehicle2);
// 显示当前停车场的车辆信息
parkingLot.displayParkingLot();
return 0;
}
在上面的示例中,我们扩展了停车场管理系统,添加了停车位类 ParkingSpot。每个停车位有一个编号和一个布尔值指示是否被占用,同时记录了停在该位上的车辆指针。
在停车场类 ParkingLot 中,我们使用了一个容量为 capacity 的 vector 来存储停车位,并初始化了每个停车位的编号。enterParkingLot() 方法用于车辆进入停车场,会找到一个未占用的停车位将车辆停入,并将停车位标记为已占用。leaveParkingLot() 方法用于车辆离开停车场,会根据车辆找到对应的停车位,并将其标记为未占用。displayParkingLot() 方法用于显示当前停车场的车辆信息,包括已停车辆和空闲停车位。
在 main() 函数中,我们创建了一个停车场对象 parkingLot,并演示了进入停车场、离开停车场和显示车辆信息的过程。
这个示例展示了一个功能丰富的停车场管理系统,你可以根据实际需求进行扩展和修改。例如,你可以添加收费功能、搜索功能、预约功能等,以满足更多的停车场管理需求。
原文地址: https://www.cveoy.top/t/topic/bWT5 著作权归作者所有。请勿转载和采集!