试用C++设计一学生校园消费记录系统
时间: 2023-10-06 20:05:59 浏览: 49
好的,以下是一个简单的学生校园消费记录系统的设计:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student {
public:
Student(string name, int id) {
this->name = name;
this->id = id;
this->balance = 0;
}
string getName() {
return name;
}
int getId() {
return id;
}
double getBalance() {
return balance;
}
void addBalance(double amount) {
balance += amount;
}
private:
string name;
int id;
double balance;
};
class Transaction {
public:
Transaction(Student* student, string type, double amount) {
this->student = student;
this->type = type;
this->amount = amount;
}
Student* getStudent() {
return student;
}
string getType() {
return type;
}
double getAmount() {
return amount;
}
private:
Student* student;
string type;
double amount;
};
class TransactionRecord {
public:
void addTransaction(Transaction* transaction) {
transactions.push_back(transaction);
}
vector<Transaction*> getTransactions() {
return transactions;
}
private:
vector<Transaction*> transactions;
};
int main() {
// 创建学生对象
Student* s1 = new Student("张三", 1001);
Student* s2 = new Student("李四", 1002);
// 进行消费记录
Transaction* t1 = new Transaction(s1, "购物", -50);
Transaction* t2 = new Transaction(s2, "充值", 100);
Transaction* t3 = new Transaction(s1, "餐饮", -30);
// 创建消费记录对象,并添加记录
TransactionRecord* record = new TransactionRecord();
record->addTransaction(t1);
record->addTransaction(t2);
record->addTransaction(t3);
// 输出每个学生的消费记录和余额
cout << s1->getName() << "的消费记录:" << endl;
double balance1 = s1->getBalance();
for (auto t : record->getTransactions()) {
if (t->getStudent() == s1) {
cout << t->getType() << "\t" << t->getAmount() << endl;
balance1 += t->getAmount();
}
}
cout << "余额:" << balance1 << endl;
cout << s2->getName() << "的消费记录:" << endl;
double balance2 = s2->getBalance();
for (auto t : record->getTransactions()) {
if (t->getStudent() == s2) {
cout << t->getType() << "\t" << t->getAmount() << endl;
balance2 += t->getAmount();
}
}
cout << "余额:" << balance2 << endl;
return 0;
}
```
该程序中,使用了三个类:`Student`表示学生,`Transaction`表示一次消费记录,`TransactionRecord`表示所有消费记录。在主函数中,首先创建两个学生对象,然后进行三次消费记录,并将其添加到消费记录对象中。最后,遍历所有消费记录,输出每个学生的消费记录和余额。
该程序还有很多可以扩展和优化的地方,例如可以添加更多的消费类型和消费限制,可以使用文件或数据库来保存消费记录等。