C++机试题: 编写一个程序,实现公交车卡类售票管理。当输入为“老年卡、“学生卡”和“普通卡”时显示不同的卡类及购票金额(老年卡”购票金额=原价“50%、学生卡”购票金额=原价”60%、“普通卡 购票金额=原价“95%) 提示: 第1步:建立公交卡类(boardingCard)的结构 第2步:创建并实现公交卡类构造函数、公交卡充值函数、公交卡余额查询函数、公交卡刷卡消费函数、创建纯虚函数用于完成刷卡种类显示和设固折扣率的操作第3步:由公交卡类派生普通卡类、学生卡类、老年卡类,并对虚函数进行重新定义
时间: 2023-12-31 13:21:05 浏览: 31
好的,以下是实现公交车卡类售票管理的 C++ 程序:
```c++
#include <iostream>
#include <string>
using namespace std;
// 公交卡类
class BoardingCard {
public:
BoardingCard(string cardType, double price, double discount) {
this->cardType = cardType;
this->price = price;
this->discount = discount;
balance = 0.0;
}
virtual void displayCardType() = 0; // 纯虚函数,用于显示卡类及购票金额
void recharge(double amount) {
balance += amount;
cout << "充值成功,当前余额:" << balance << "元" << endl;
}
void queryBalance() {
cout << "当前余额:" << balance << "元" << endl;
}
void consume() {
double amount = price * discount;
if (balance >= amount) {
balance -= amount;
cout << "购票成功,票价:" << amount << "元,当前余额:" << balance << "元" << endl;
} else {
cout << "余额不足,请充值后再购买车票" << endl;
}
}
protected:
string cardType; // 卡类
double price; // 原价
double discount; // 折扣率
double balance; // 余额
};
// 普通卡类
class NormalCard : public BoardingCard {
public:
NormalCard() : BoardingCard("普通卡", 2.0, 0.95) {}
void displayCardType() {
cout << "当前卡类:" << cardType << ",购票金额:" << price * discount << "元" << endl;
}
};
// 学生卡类
class StudentCard : public BoardingCard {
public:
StudentCard() : BoardingCard("学生卡", 2.0, 0.6) {}
void displayCardType() {
cout << "当前卡类:" << cardType << ",购票金额:" << price * discount << "元" << endl;
}
};
// 老年卡类
class ElderlyCard : public BoardingCard {
public:
ElderlyCard() : BoardingCard("老年卡", 2.0, 0.5) {}
void displayCardType() {
cout << "当前卡类:" << cardType << ",购票金额:" << price * discount << "元" << endl;
}
};
int main() {
string cardType;
cout << "请输入卡类(老年卡/学生卡/普通卡):" << endl;
cin >> cardType;
BoardingCard* card;
if (cardType == "老年卡") {
card = new ElderlyCard();
} else if (cardType == "学生卡") {
card = new StudentCard();
} else {
card = new NormalCard();
}
card->displayCardType();
double amount;
cout << "请输入充值金额:" << endl;
cin >> amount;
card->recharge(amount);
card->queryBalance();
card->consume();
delete card;
return 0;
}
```
运行结果:
```
请输入卡类(老年卡/学生卡/普通卡):
普通卡
当前卡类:普通卡,购票金额:1.9元
请输入充值金额:
10
充值成功,当前余额:10元
当前余额:10元
购票成功,票价:1.9元,当前余额:8.1元
```