火车订票系统面向对象C++的代码
时间: 2023-08-27 13:05:40 浏览: 102
C++火车票预订系统
以下是一个简单的火车订票系统的面向对象C++代码示例:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Train {
private:
string name;
int max_passengers;
vector<string> passengers;
public:
Train(string name, int max_passengers) {
this->name = name;
this->max_passengers = max_passengers;
}
string getName() {
return name;
}
int getMaxPassengers() {
return max_passengers;
}
int getNumPassengers() {
return passengers.size();
}
bool addPassenger(string passenger) {
if(passengers.size() >= max_passengers) {
return false;
}
passengers.push_back(passenger);
return true;
}
};
int main() {
Train train("K123", 50);
cout << "Welcome to train booking system. Train " << train.getName() << " can take " << train.getMaxPassengers() << " passengers." << endl;
while(true) {
string command;
cout << "Enter command (book, status, exit): ";
cin >> command;
if(command == "book") {
string passenger;
cout << "Enter passenger name: ";
cin >> passenger;
if(train.addPassenger(passenger)) {
cout << "Booking successful." << endl;
} else {
cout << "Booking failed. Train is full." << endl;
}
} else if(command == "status") {
cout << "Train " << train.getName() << " has " << train.getNumPassengers() << " passengers." << endl;
} else if(command == "exit") {
break;
} else {
cout << "Invalid command. Please try again." << endl;
}
}
return 0;
}
```
这个程序定义了一个Train类,它有一个名称,最大乘客数和一个存储乘客名字的向量。类中有一些方法,例如addPassenger()将一个乘客名字添加到向量中,getNumPassengers()返回当前已订票的乘客数。在主函数中,程序通过输入不同的命令(book,status或exit)来与用户交互。如果输入book命令,则程序将要求输入乘客姓名并将其添加到Train对象中。如果输入status命令,则程序将打印当前已订票的乘客数。如果输入exit命令,则程序将退出。
阅读全文