您的位置:首页 > 编程语言 > C语言/C++

C++primer plus 编程练习10.10

2016-03-06 15:05 441 查看
编程练习:

1.定义一个类来表示银行账户。数据成员包括出乎姓名、账

号(使用字符串)和存款。成员函数执行如下操作:

*创建一个对象并将其初始化;

*显示储户姓名、账号和存款;

*存入参数指定的存款;

*取出参数指定的款项;

编写一个小程序来显示所有的特性。

程序编写如下:

//文件Bankaccount.h
class Bankaccount
{
private:
char name[40];
char acctnum[25];
double balance;
public:
Bankaccount(const char* client, const char* num, double bal = 0.0);
void show(void) const;
void deposit(double cash);
void withdraw(double cash);
};

//文件Bankaccount.cpp
#include "Bankaccount.h"
#include<string.h>
#include<iostream>
Bankaccount::Bankaccount(const char* client, const char* num, double bal)
{
strncpy(name, client,39);
name[39]='\0';
strncpy(acctnum,num,24);
acctnum[24]='\0';
balance=bal;
}

void Bankaccount::show(void) const
{
using std::cout;
cout<<"Name: "<<name<<" Acctnum: "<<acctnum<<" balance: "<<balance<<"\n";
}

void Bankaccount::deposit(double cash)
{
using std::cout;
if(cash<0)
cout<<"Number of balance deposited can't be negative. ";
else    balance+=cash;

}

void Bankaccount::withdraw(double cash)
{
using std::cout;
if(cash<0) cout<<"Number of balance withdrawed can't be negative. ";
else if(cash>balance)
cout<<"You can't withdraw more than you have. ";

//文件Bankaccount1.cpp
#include<iostream>
#include<cctype>
#include"Bankaccount.h"
int main()
{
using namespace std;
Bankaccount banka1("zhang san","24536",19804);
banka1.show();
double cash1;
char ch;
cout<<"Do you want to deposit or withdraw money? "
<<"Please choose d to deposit money, choose w to withdraw money or choose q to quit. ";
while(cin>>ch&&toupper(ch)!='Q')
{
while(cin.get()!='\n')
continue;
if(!isalpha(ch))
{
cout<<'\a';
continue;
}
switch(ch)
{
case 'd':
case 'D':
cout<<"Please enter the number of money you deposit: ";
cin>>cash1;
banka1.deposit(cash1);
banka1.show();
break;
case 'w':
case 'W':
cout<<"Please enter the number of money you withdraw: ";
cin>>cash1;
banka1.withdraw(cash1);
banka1.show();
break;
}

}
system("pause");
return 0;
}


程序运行结果满足预期要求。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: