C++编程实践: 继承与多态
本实例及代码来自《C++ Primer Plus》(第六版) 第十三章
题目要求:
假如你是某银行首席程序员。银行要求你开发两个类,一个用于表示基本支票账户——Brass Account,另一个用于表示代表Brass Plus支票账户,它添加了透支保护的特性。也就是说,如果持有此卡的用户签出了一张超出其存款余额的支票——但是超出的数额并不是很大,银行将支付这张支票,对超出的部分收取额外的费用,并追加罚款。
下面是用于Brass Account支票账户的信息:
- 客户姓名
- 帐号
- 当前结余
- 创建帐号
- 存款
- 取款
- 显示账户信息
- 透支上限
- 透支贷款利率
- 当前透支总额
不需要新的操作,但有两种操作的实现不同
- 对于取款,必须考虑透支保护
- 显示账户信息必须包括Brass Plus账户的基本信息以及相对于Brass账户的其他信息
银行提供的额外信息包括
- Brass Plus账户限制了客户的透支金额,默认为500,但银行可修改
- Brass Plus账户对贷款收取利息,默认为11.125%,但银行可修改
- 账户欠下的金额不能通过存款或转账还清,需要银行柜员手动设置清零(为了编程方便
思路分析:
-
假定将第一个类命名为Brass, 第二个类为BrassPlus。他们两个的关系满足is-a关系,所以应该从Brass公有派生出BrassPlus。它们都将保存客户的姓名,帐号和结余。使用这两个类都可以存款,取款和显示帐号信息。
- 新的类需要新的构造函数,而且该构造函数应该能够提供账户信息,设置透支上限和利率。另外还应该具有重新设置透支金额,利率和当前欠款的方法。
知识点:
-
类BrassPlus公有继承自类Brass,声明格式如下:
class BrassPlus : public Brass
- 派生类的构造函数必须使用基类的构造函数,创建派生类对象的时候,程序将首先调用基类的构造函数,再构造派生类的构造函数:
BrassPlus::BrassPlus(const std::string & s, long an, double bal, double ml, double r) :Brass(s, an, bal)
{
maxLoan = ml;
owesBank = 0.0;
rate = r;
}
BrassPlus::BrassPlus(const Brass &ba, double ml, double r) :Brass(ba)
{
maxLoan = ml;
owesBank = 0.0;
rate = r;
}
- 派生类可以直接使用基类的方法,条件是该方法不是私有的。
- 基类指针可以在不进行显式转换的情况下指向派生类对象。
- 基类的Withdraw,ViewAcct和析构函数之前都加了virtual关键字,这表明这三个方法是虚的。使用virtual关键字的好处是:如果没有使用关键字virtual,程序将根据引用类型或指针类型选择方法,如果使用了关键字virtual,则程序将根据引用或指针指向的对象的类型来选择方法。下面的代码片很好的说明了这种关系:
Brass * p_clients[2];
p_clients[0] = new Brass("Tim", 112233, 1500);
p_clients[1] = new BrassPlus("Tim", 112233, 1500, 500, 0.11125);
p_clients[0]->ViewAcct();//use Brass::ViewAcct()
p_clients[1]->ViewAcct();//use BrassPlus::ViewAcct() because Brass::ViewAcct() is a virtual function
- 一个惯例是: 如果要在派生类中重新定义基类方法,通常应该将基类的方法声明为虚的。这样程序将根据对象类型而不是引用或指针类型来选择方法的版本。为基类声明一个虚的析构函数也是一种惯例。使用虚析构函数可以保证正确的析构函数调用顺序。
- 关键字virtual 只能用在类声明的方法原型中(即.h文件中声明的时候),而不能用在方法定义中
- 可以使用cout的格式化方法来设置输出的格式:
format setFormat() {
//set ###.## format
return cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
}
void restore(format f, precis p) {
//reset the format and precision
cout.setf(f, std::ios_base::floatfield);
cout.precision(p);
}
- 需要知道编译器对于非虚方法使用的是静态联编,对虚方法使用的是动态联编。
总结:
-
继承和多态是面向对象变成中非常重要的概念,在C++中由于指针和引用的存在,对类和继承有很多需要注意的处理方法,尤其是虚函数。
-
需要注意对于派生类中的构造函数的处理,派生类中的构造函数必须调用基类的构造函数。
- 为了保证析构函数的调用顺序,应该将基类的析构函数定义为虚函数。
- 使用虚函数之后便可以使用指针数组保存基类对象和派生类对象混合的数据结构,下面的主函数对其专门进行了测试。
源代码:
brass.h
#pragma once
#ifndef BRASS_H_
#define BRASS_H_
#include <string>
class Brass
{
private:
std::string fullName;
long accNum;
double balance;
public:
Brass(const std::string & s = "Nullbody", long an = -1, double bal = 0.0);
void Deposit(double amt);
virtual void Withdraw(double amt); //virtual function
double Balance() const;
virtual void ViewAcct() const; //virtual function
virtual ~Brass() {};//virtual function
};
class BrassPlus : public Brass
{
private:
double maxLoan;
double rate;
double owesBank;
public:
BrassPlus(const std::string & s = "Nullbody", long an = -1, double bal = 0.0, double ml = 500, double r = 0.11125);
BrassPlus(const Brass &ba, double ml = 500, double r = 0.11125);
virtual void ViewAcct() const;
virtual void Withdraw(double amt);
void ResetMax(double m) { maxLoan = m; };
void ResetRate(double r) { rate = r; };
void ReserOwes() { owesBank = 0; };
};
#endif
brass.cpp
#include"brass.h"
#include<iostream>
using std::cout;
using std::endl;
using std::string;
typedef std::ios_base::fmtflags format;
typedef std::streamsize precis;
format setFormat();
void restore(format f, precis p);
Brass::Brass(const std::string & s, long an, double bal) {
fullName = s;
accNum = an;
balance = bal;
}
void Brass::Deposit(double amt) {
if (amt < 0)
cout << "Negative deposit not allowed; " << "deposit is cancelled.\n";
else
balance += amt;
}
void Brass::Withdraw(double amt) {
format initialState = setFormat();
precis prec = cout.precision(2);
if (amt < 0) {
cout << "Withdrawal amount must be positive; " << "withdrawal cancelled.\n";
}
else if (amt <= balance)
balance -= amt;
else
cout << "Withdrawal amount of $" << amt
<< " exceeds your balance.\n"
<< "Withdrawal cancelled.\n";
restore(initialState, prec);
}
double Brass::Balance() const {
return balance;
}
void Brass::ViewAcct() const {
format initialState = setFormat();
precis prec = cout.precision(2);
cout << "Client: " << fullName << endl;
cout << "Account number: " << accNum << endl;
cout << "Balance: $" << balance << endl;
restore(initialState, prec);
}
BrassPlus::BrassPlus(const std::string & s, long an, double bal, double ml, double r) :Brass(s, an, bal)
{
maxLoan = ml;
owesBank = 0.0;
rate = r;
}
BrassPlus::BrassPlus(const Brass &ba, double ml, double r) :Brass(ba)
{
maxLoan = ml;
owesBank = 0.0;
rate = r;
}
void BrassPlus::ViewAcct() const {
format initialState = setFormat();
precis prec = cout.precision(2);
Brass::ViewAcct();
cout << "MaxLoan: $" << maxLoan << endl;
cout << "Owed to Bank $" << owesBank << endl;
cout.precision(3);
cout << "Loan Rate: " << 100*rate <<"%"<< endl;
restore(initialState, prec);
}
void BrassPlus::Withdraw(double amt) {
format initialState = setFormat();
precis prec = cout.precision(2);
double bal = Balance();
if (amt <= bal) {
Brass::Withdraw(amt);
}
else if (amt <= bal + maxLoan - owesBank) {
double advance = amt - bal;
owesBank += advance*(1.0 + rate);
cout << "Bank Advance: $" << endl;
cout << "Finance Charge: $" << advance*rate << endl;
Deposit(advance);
Brass::Withdraw(amt);
}
else
cout << "Credit limit exceedsed, Transaction cancelled.\n";
restore(initialState, prec);
}
format setFormat() {
//set ###.## format
return cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
}
void restore(format f, precis p) {
//reset the format and precision
cout.setf(f, std::ios_base::floatfield);
cout.precision(p);
}
main.cpp
#include<iostream>
#include"brass.h"
#include<string>
#pragma warning(disable:4996)
const int CLIENTS = 4;
int main(void) {
// freopen("Text.txt", "r", stdin);
using std::cin;
using std::cout;
using std::endl;
Brass * p_clients[CLIENTS];
std::string temp;
long tempnum;
double tempbal;
char kind;
for (int i = 0; i < CLIENTS; i++) {
cout << "Enter client`s name: ";
getline(cin, temp);
cout << "Enter client`s account number: ";
cin >> tempnum;
cout << "Enter opening balance: $";
cin >> tempbal;
cout << "Enter 1 for Brass Account or 2 for BrassPlus Account: ";
while (cin>>kind&&(kind!='1'&&kind!='2'))
{
cout << "Enter either 1 or 2: ";
}
if (kind == '1')
p_clients[i] = new Brass(temp, tempnum, tempbal);
else {
double tmax, trate;
cout << "Enter the overdraft limit: $";
cin >> tmax;
cout << "Enter the interest rate as a decimal function: ";
cin >> trate;
p_clients[i] = new BrassPlus(temp, tempnum, tempbal, tmax, trate);
}
while (cin.get()!='\n')
{
continue;
}
}
for (int i = 0; i < CLIENTS; i++) {
cout << endl;
p_clients[i]->ViewAcct();
}
for (int i = 0; i < CLIENTS; i++) {
delete p_clients[i];
}
cout << "Done!!";
return 0;
}
测试结果: