【C++OJ_单继承】存折与信用卡(继承)
题目描述
定义一个存折类CAccount,存折类具有帐号(account, long)、姓名(name,char[10])、余额(balance,float)等数据成员,可以实现存款(deposit,操作成功提示“saving ok!”)、取款(withdraw,操作成功提示“withdraw ok!”)和查询余额(check)的操作,取款金额必须在余额范围内,否则提示“sorry! over balance!”。
从存折类派生出信用卡类CCreditcard,信用卡类增加了透支限额(limit,float)一项数据成员,对取款操作进行修改,允许在限额范围内透支金额,超出范围取款提示“sorry! over limit!”。注意,在本题中,balance可以是负数,例如当余额为500,可透支金额为500,取款800时,则balance为 - 300。
编写主函数,建立这两个类的对象并测试之。
1.对于存折类,输入账号、姓名、余额后,按照查询余额、存款、查询余额、取款、查询余额的顺序调用类方法并输出。
2.对于信用卡类,输入账号、姓名、余额、透支限额后,按照查询余额、存款、查询余额、取款、查询余额的顺序调用类方法并输出。
输入
账号 姓名 余额
存款金额
取款金额
账号 姓名 余额 透支限额
存款金额
取款金额
输出
账户余额
存款操作结果
账户余额
取款操作结果
账户余额
账户余额
存款操作结果
账户余额
取款操作结果
账户余额
输入样例
1000 Tom 1000
500
1000
2000 John 500 500
500
1501
输出样例
balance is 1000
saving ok!
balance is 1500
withdraw ok!
balance is 500
balance is 500
saving ok!
balance is 1000
sorry! over limit!
balance is 1000
参考代码
#include <iostream>
#include <cstring>
using namespace std;
class CAccount //存折类CAccount
{
protected:
long account; //帐号
char name[10]; //姓名
float balance; //余额
public:
CAccount(long A, char N[], float B) : account(A), balance(B) //构造函数,初始化参数列表
{
strcpy(name, N); //使用char需要使用strcpy
}
void deposit(float x) //存款(deposit,操作成功提示“saving ok!”)
{
balance += x;
cout << "saving ok!" << endl;
}
void withdraw(float x) //取款(withdraw,操作成功提示“withdraw ok!”)
{
if (x <= balance)
{
balance -= x;
cout << "withdraw ok!" << endl;
}
else //取款金额必须在余额范围内,否则提示“sorry! over balance!”。
cout << "sorry! over balance!" << endl;
}
float check() //查询余额(check)的操作
{
return balance;
}
};
class CCreditcard : public CAccount //从存折类派生出信用卡类CCreditcard
{
protected:
float limit; //信用卡类增加了透支限额(limit,float)一项数据成员
public:
CCreditcard(long A, char N[], float B, float L) : CAccount(A, N, B), limit(L) //构造函数,初始化参数列表
{
}
void withdraw(float x) // 对取款操作进行修改
{
if (x - balance <= limit) //允许在限额范围内透支金额
{
balance -= x; // balance可以是负数
cout << "withdraw ok!" << endl;
}
else //超出范围取款提示“sorry! over limit!”。
cout << "sorry! over limit!" << endl;
}
};
int main()
{
long account;
char name[10];
float balance;
float x, y, limit;
cin >> account >> name >> balance; //对于存折类,输入账号、姓名、余额
cin >> x >> y; //输入存款金额和取款金额
CAccount A(account, name, balance); //构造存折类对象
cout << "balance is " << A.check() << endl; //查询余额
A.deposit(x); //存款
cout << "balance is " << A.check() << endl; //查询余额
A.withdraw(y); //取款
cout << "balance is " << A.check() << endl; //查询余额
cin >> account >> name >> balance >> limit; //对于信用卡类,输入账号、姓名、余额、透支限额
cin >> x >> y; //输入存款金额和取款金额
CCreditcard C(account, name, balance, limit); //信用卡类对象,后面操作同理
cout << "balance is " << C.check() << endl;
C.deposit(x);
cout << "balance is " << C.check() << endl;
C.withdraw(y);
cout << "balance is " << C.check() << endl;
return 0;
}