C++编写一个程序,实现公交车卡类售票管理。当输入为“老年卡”、学生卡”和“普通卡”时显示不同的卡类及购票金额(老年卡”购票金额=原价”50%、“学生卡”购票金额=原价“60%、“普通卡”购票金额=原价*95% 提示: 第1步:建立公交卡类(boardingCard)的结构。 第2步:创建并实现公交卡类构造函数、公交卡充值函数、公交卡余额查询函数、公交卡刷卡消费函数、创建纯虚函数用于完成刷卡种类显示和设置折扣率的操作。 第3步:由公交卡类派生普通卡类、学生卡类、老年卡类,并对虚函数进行重新定义。第4步:定义主函数进行测试。
时间: 2023-12-31 17:22:45 浏览: 29
以下是一个可能的实现:
```c++
#include <iostream>
#include <string>
using namespace std;
class BoardingCard {
protected:
double balance;
public:
BoardingCard(double b = 0) : balance(b) {}
void charge(double amount) { balance += amount; }
double getBalance() const { return balance; }
virtual double getDiscount() const = 0; // 纯虚函数,用于设置折扣率
virtual string getType() const = 0; // 纯虚函数,用于显示卡类
virtual double getPrice(double original) const { // 根据折扣率计算购票金额
return original * getDiscount();
}
virtual ~BoardingCard() {} // 基类析构函数需要为虚函数
};
class NormalCard : public BoardingCard {
public:
NormalCard(double b = 0) : BoardingCard(b) {}
double getDiscount() const override { return 0.95; }
string getType() const override { return "普通卡"; }
};
class StudentCard : public BoardingCard {
public:
StudentCard(double b = 0) : BoardingCard(b) {}
double getDiscount() const override { return 0.6; }
string getType() const override { return "学生卡"; }
};
class ElderlyCard : public BoardingCard {
public:
ElderlyCard(double b = 0) : BoardingCard(b) {}
double getDiscount() const override { return 0.5; }
string getType() const override { return "老年卡"; }
double getPrice(double original) const override { // 老年卡购票金额特殊计算
return original * getDiscount() * 2;
}
};
int main() {
BoardingCard* card = nullptr;
string type;
double price = 10;
cout << "请输入卡类(老年卡、学生卡、普通卡):";
cin >> type;
if (type == "老年卡") {
card = new ElderlyCard();
} else if (type == "学生卡") {
card = new StudentCard();
} else if (type == "普通卡") {
card = new NormalCard();
} else {
cout << "无效的卡类!" << endl;
return 0;
}
cout << "请输入购票金额:";
cin >> price;
double discount = card->getDiscount();
cout << "您选择的是" << card->getType() << ",购票金额为" << card->getPrice(price) << "元(" << discount * 100 << "%折扣)" << endl;
delete card;
return 0;
}
```
这个程序定义了一个公交卡类 `BoardingCard`,包括基本信息(余额)、充值、余额查询、刷卡消费等操作,以及用于设置折扣率、显示卡类和计算购票金额的纯虚函数。然后从 `BoardingCard` 派生出三个子类,分别实现不同的折扣率和计算购票金额的方式,以及显示不同的卡类名称。在主函数中,根据用户输入的卡类和购票金额,动态创建相应的卡对象,并根据对象调用虚函数,显示购票金额和折扣率。最后释放动态分配的对象。
需要注意的是,程序中使用了动态内存分配,需要手动释放内存,以避免内存泄漏。同时,基类的析构函数必须为虚函数,以便在使用基类指针释放派生类对象时,能够调用正确的析构函数,避免多态问题。