为复习题5描述的类提供方法定义,并编写一个小程序来演示所有的特性。
复习题5:定义一个类来表示银行账户。数据成员包括储户姓名、账号(使用字符串)和存款。成员函数执行如下操作:
- 创建一个对象并将其初始化;
- 显示储户姓名、账号和存款;
- 存入参数指定的存款;
- 取出参数指定的款项。
请提供类声明,而不用给出方法实现。
类声明:BankAccount.h
#ifndef BANKACCOUNT_H_
#define BANKACCOUNT_H_
#include <iostream>
class BankAccount
{
private:
std::string name;
std::string account;
double balance;
public:
BankAccount(); //默认构造函数
BankAccount(const std::string & name1, const std::string & account, const double balance1);
void show() const;
bool withdraw(double cash); //取款
bool deposit(double cash); //存款
~BankAccount(); //析构函数
};
#endif
类成员函数: BankAccount.cpp
#include <iostream>
#include "BankAccount.h"
BankAccount::BankAccount() //默认构造函数
{};
BankAccount::BankAccount(const std::string& name, const std::string& account, const double balance)
{
this->name = name;
this->account = account;
this->balance = balance;
}
BankAccount::~BankAccount() //析构函数
{
std::cout << "Bye!" << name << "\n";
}
bool BankAccount::deposit(double cash) //存钱
{
balance += cash;
return true;
}
bool BankAccount::withdraw(double cash) //取钱
{
if (balance > cash)
{
balance -= cash;
return true;
}
else
{
std::cout << "The balance is insufficient!!\n";
return false;
}
}
void BankAccount::show() const
{
using std::cout;
using std::endl;
cout << "Name: " << name << endl;
cout << "Account: " << account << endl;
cout << "Banlance: " << balance << endl;
}
举例:Bank.cpp
#include <iostream>
#include "BankAccount.h"
int main()
{
BankAccount bankAccount("AAA", "0001", 1000);
bankAccount.show();
bankAccount.deposit(120.5);
bankAccount.show();
bankAccount.withdraw(1500);
bankAccount.show();
bankAccount.withdraw(1000);
bankAccount.show();
return 0;
}
实例:Bank.cpp
#include <iostream>
#include "BankAccount.h"
int main()
{
BankAccount bankAccount("AAA", "0001", 1000);
bankAccount.show();
bankAccount.deposit(120.5);
bankAccount.show();
bankAccount.withdraw(1500);
bankAccount.show();
bankAccount.withdraw(1000);
bankAccount.show();
return 0;
}
运行结果: