C++ PRIMER PLUS (第5版)习题10.1

为复习题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;
}

 

运行结果:

 

 

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值