用面向对象C++写一个饭卡管理系统,要求定义对象,并用对象调用类函数
时间: 2024-05-04 21:18:37 浏览: 12
好的,以下是一个简单的饭卡管理系统的面向对象C++代码:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义饭卡类
class MealCard {
private:
string name; // 持卡人姓名
float balance; // 卡余额
public:
// 构造函数
MealCard(string n, float b) {
name = n;
balance = b;
}
// 获取卡余额
float getBalance() {
return balance;
}
// 充值
void recharge(float amount) {
balance += amount;
cout << "充值成功,当前余额为:" << balance << endl;
}
// 消费
void consume(float amount) {
if (balance < amount) {
cout << "余额不足,无法完成消费!" << endl;
} else {
balance -= amount;
cout << "消费成功,当前余额为:" << balance << endl;
}
}
// 获取持卡人姓名
string getName() {
return name;
}
};
int main() {
// 创建饭卡对象
MealCard card("小明", 100.0);
// 获取卡余额
cout << card.getName() << "的卡余额为:" << card.getBalance() << endl;
// 充值
card.recharge(50.0);
// 消费
card.consume(80.0);
return 0;
}
```
在上面的代码中,我们定义了一个饭卡类 `MealCard`,其中包含了持卡人的姓名和卡的余额两个私有成员变量,以及充值、消费、获取余额、获取姓名四个公有成员函数。在 `main` 函数中,我们创建了一个名为 `card` 的饭卡对象,并调用了其相关的成员函数。