C++ 面向对象 ATM 系统设计与实现
以下是一个简单的基于面向对象思想的 ATM 系统设计与实现的 C++ 程序示例:
#include <iostream>
#include <string>
using namespace std;
class Account {
private:
string accountNumber;
string pin;
double balance;
public:
Account(string accountNumber, string pin, double balance) {
this->accountNumber = accountNumber;
this->pin = pin;
this->balance = balance;
}
string getAccountNumber() {
return accountNumber;
}
bool validatePin(string enteredPin) {
return pin == enteredPin;
}
double getBalance() {
return balance;
}
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
cout << 'Insufficient balance' << endl;
}
}
};
class ATM {
private:
Account* account;
public:
void insertCard(Account* account) {
this->account = account;
}
void ejectCard() {
account = nullptr;
}
bool isCardInserted() {
return account != nullptr;
}
void enterPin(string pin) {
if (account->validatePin(pin)) {
showMenu();
} else {
cout << 'Invalid pin' << endl;
}
}
void showBalance() {
cout << 'Balance: ' << account->getBalance() << endl;
}
void deposit(double amount) {
account->deposit(amount);
cout << 'Deposit successful' << endl;
}
void withdraw(double amount) {
account->withdraw(amount);
}
void showMenu() {
int choice;
double amount;
while (true) {
cout << '1. Check balance' << endl;
cout << '2. Deposit' << endl;
cout << '3. Withdraw' << endl;
cout << '4. Eject card' << endl;
cout << 'Enter your choice: ';
cin >> choice;
switch (choice) {
case 1:
showBalance();
break;
case 2:
cout << 'Enter amount to deposit: ';
cin >> amount;
deposit(amount);
break;
case 3:
cout << 'Enter amount to withdraw: ';
cin >> amount;
withdraw(amount);
break;
case 4:
ejectCard();
return;
default:
cout << 'Invalid choice' << endl;
}
}
}
};
int main() {
Account account('123456789', '1234', 1000.0);
ATM atm;
atm.insertCard(&account);
if (atm.isCardInserted()) {
string pin;
cout << 'Enter pin: ';
cin >> pin;
atm.enterPin(pin);
}
return 0;
}
这个程序包含两个类:Account 和 ATM。Account 类表示银行账户,包含账号、PIN 码和余额等信息,以及相关的操作方法。ATM 类表示 ATM 机,包含插入卡片、验证 PIN 码、显示余额、存款、取款等操作方法,并提供一个菜单供用户选择操作。
在主函数中,首先创建一个 Account 对象代表用户的账户,然后创建一个 ATM 对象。通过调用 ATM 对象的插入卡片方法将账户对象传递给 ATM,然后要求用户输入 PIN 码进行验证。如果验证通过,ATM 将显示菜单供用户选择操作。
请注意,这只是一个简单的示例,可以根据实际需求进行扩展和改进。
原文地址: https://www.cveoy.top/t/topic/pkUs 著作权归作者所有。请勿转载和采集!