C++停车场管理系统:车辆出入管理代码实现
C++停车场管理系统:车辆出入管理代码实现
本篇博客将用C++编写一个简单的停车场管理系统,实现车辆的出入管理功能。
以下是代码示例:
#include <iostream>
#include <vector>
using namespace std;
class Vehicle {
public:
string licensePlate;
string brand;
Vehicle(string licensePlate, string brand) {
this->licensePlate = licensePlate;
this->brand = brand;
}
};
class ParkingLot {
private:
vector<Vehicle> vehicles;
int capacity;
public:
ParkingLot(int capacity) {
this->capacity = capacity;
}
void parkVehicle(Vehicle vehicle) {
if (vehicles.size() < capacity) {
vehicles.push_back(vehicle);
cout << 'Vehicle with license plate ' << vehicle.licensePlate << ' parked successfully.' << endl;
} else {
cout << 'Parking lot is full. Cannot park vehicle with license plate ' << vehicle.licensePlate << endl;
}
}
void removeVehicle(string licensePlate) {
for (int i = 0; i < vehicles.size(); i++) {
if (vehicles[i].licensePlate == licensePlate) {
vehicles.erase(vehicles.begin() + i);
cout << 'Vehicle with license plate ' << licensePlate << ' removed successfully.' << endl;
return;
}
}
cout << 'Vehicle with license plate ' << licensePlate << ' not found.' << endl;
}
void printVehicles() {
cout << 'Vehicles in the parking lot:' << endl;
for (int i = 0; i < vehicles.size(); i++) {
cout << 'License Plate: ' << vehicles[i].licensePlate << ', Brand: ' << vehicles[i].brand << endl;
}
}
};
int main() {
ParkingLot parkingLot(5);
Vehicle vehicle1('ABC123', 'Toyota');
Vehicle vehicle2('XYZ789', 'Honda');
Vehicle vehicle3('DEF456', 'Ford');
parkingLot.parkVehicle(vehicle1);
parkingLot.parkVehicle(vehicle2);
parkingLot.parkVehicle(vehicle3);
parkingLot.printVehicles();
parkingLot.removeVehicle('XYZ789');
parkingLot.printVehicles();
return 0;
}
代码解释:
- Vehicle类: 表示车辆,包含车牌号(licensePlate)和品牌(brand)属性。
- ParkingLot类: 表示停车场,包含车辆列表(vehicles)和容量(capacity)属性,以及停车(parkVehicle)、取车(removeVehicle)和打印车辆信息(printVehicles)方法。
- main函数: 创建一个容量为5的停车场对象,添加三辆车并进行测试。
代码分析
- 程序通过定义
Vehicle和ParkingLot类,模拟了现实世界中的车辆和停车场。 ParkingLot类中的方法,例如parkVehicle和removeVehicle,清晰地展现了停车场管理系统的核心功能。- 示例代码中使用了
vector来存储车辆信息,方便进行添加、删除和遍历操作。
总结
这是一个简单的C++停车场管理系统示例代码,实际应用中需要根据具体需求进行扩展,例如:
- 添加费用计算功能
- 实现数据库对接,持久化存储车辆信息
- 设计用户界面,提升用户体验
原文地址: http://www.cveoy.top/t/topic/f337 著作权归作者所有。请勿转载和采集!