当前位置: 首页 > news >正文

《C++大学教程》3.12Account类

题目:

(Account类)创建一个名为Account 的类,银行可以使用它表示客户的银行账户。这个类应该包括一个类型为int 的数据成员,表示账户余额。【注意:在后续章节中,将使用称为浮点值的包含小数点的数(例如2.75)表示美元数。】

  • 这个类必须提供一个构造函数,它接收初始余额并用它初始化数据成员。这个构造函数应当确认初始余额的有效性,保证它大于或等于0。否则,余额应当设置为0并且构造函数必须显示一条错误信息,指出初始余额是无效的。
  • 该类还要提供三个成员函数。
  1.      成员函数 credit将一笔金额加到当前余额中。
  2.      debit 将从这个 Account 中取钱,并保证取出金额不超过此Account的余额。如果不是这样,余额不变函数打印一条信息,指出“Debit amount”。
  3.      成员函数getBalance将返回当前余额。编写一个测试程序,它创建两exceeded account balance.个Account对象,并测试Account类的成员函数

代码:

//Account.h#include <iostream>
#include <string>
// 不能使用using声明class Account
{public:Account(){ // 构造函数保证数据的有效性setBalance();};void setBalance(){int num;std::cout << "请输入初始余额:";std::cin >> num;if (num < 0){num = 0;std::cout << "初始余额是无效的。";}accountBalance = num;}int getBalance() const // 查询余额{return accountBalance;}void credit(){ // 存钱int num;std::cout << "请输入存入的金额:";std::cin >> num;accountBalance += num;}void debit(){ // 取钱int num;std::cout << "请输入取出的金额:";std::cin >> num;if (num > getBalance()){std::cout << "Debit amount exceeded account balance(取款数目超过了账户余额).\n";}else{accountBalance -= num;}}private:int accountBalance;
};
//3.12account.cpp#include <iostream>
#include "Account.h"
#include <string>
using namespace std;int main()
{cout << "请输入对account1的操作:" << endl;Account account1;cout << "The account1 initial balance is " << account1.getBalance() << endl;account1.credit();account1.debit();cout << "The account1 now balance is " << account1.getBalance() << endl;cout << endl;cout << "请输入对account2的操作:" << endl;Account account2;cout << "The account2 initial balance is " << account2.getBalance() << endl;account2.credit();account2.debit();cout << "The account2 now balance is " << account2.getBalance() << endl;return 0;
}

运行截图:

http://www.lryc.cn/news/283932.html

相关文章:

  • 【工作记录】基于springboot3+springsecurity实现多种方式登录及鉴权(二)
  • CSS笔记III
  • Bit.Store 加密卡集成主流 BRC20通证,助力 BTC 生态流动性
  • openssl3.2 - 官方demo学习 - mac - siphash.c
  • (六)深入理解Bluez协议栈之“GATT Client Profile”
  • SVO编译
  • 探索未知:最新发布的顶级浏览器,为你带来前所未有的浏览体验
  • EasyX图形化学习(三)
  • git-生成证书、公钥、私钥、error setting certificate verify locations解决方法
  • 论文笔记(四十)Goal-Auxiliary Actor-Critic for 6D Robotic Grasping with Point Clouds
  • k8s学习-Deployment
  • Unity之四元数
  • 【计算机硬件】3、输入输出技术、总线结构
  • k8s的对外服务--ingress
  • CSS 雷达监测效果
  • C# System.MissingMethodException
  • Redis面试题23
  • Linux中的yum源仓库和NFS文件共享服务
  • 【LeetCode2744】最大字符串配对数目
  • 安全加速SCDN是什么
  • Android 布局菜鸟 android中的布局类型和特点?
  • 2023总结与2024寒假计划
  • 016-Vue-黑马2023:前后端分离开发(在线接口文档),前端工程化、Element、vue编写一个完成页面、Vue路由、vue打包部署到nginx
  • 如何给新华网投稿发稿?新华网的媒体发稿方法步骤
  • 为什么 macOS 比 Windows 稳定?
  • 从matlab的fig图像文件中提取数据
  • 基于网络爬虫的微博热点分析,包括文本分析和主题分析
  • 前端图片转base64 方法
  • Go语言数据结构(一)双向链表
  • 【MySql】MySQL 如何创建新用户