RatedPlayer继承示例很简单,可参考https://blog.csdn.net/merry1996/article/details/100066859。派生类对象使用基类的方法,而未做任何修改。然而,可能会遇到这样的情况,即希望同一个方法在派生类和基类中的行为是不同的。换句话来说,方法的行为应取决于调用该方法的对象。这种较复杂的行为称为多态---具有多种形态,即同一个方法的行为随上下文而异。
有两种重要的机制可用于实现多态公有继承:
- 在派生类中重新定义基类的方法
- 使用虚方法
现在来看另一个例子。由于Webtown俱乐部的工作经历,您成为了Pontoon银行的首席程序员。银行要求您完成的第一项工作是开发两个类。一个类用于表示基本支票账户---Brass Account,另一个类用于表示代表 Brass Plus支票账户,它添加了支票保护特性。
也就是说,如果客户签出一张超出其存款余额的支票---但是超出的数额并不是很大,银行将支付这张支票,对超出的部分收取额外的费用,并追加罚款。可以根据要保存的数据以及允许执行的操作来确定这两种账户的特征。
下面是用于Brass Account支票账户的信息:
- 客户姓名
- 账号
- 当前结余
下面是可执行的操作:
- 创建账户
- 存款
- 取款
- 显示账户信息
Pontoon银行希望Brass Plus支票账户包含Brass Account的所有信息及如下信息:
- 透支上限
- 透支贷款利率
- 当前的透支总额
不需要新操作,但是有两种操作的实现不同:
- 对于取款操作,必须考虑透支保护
- 显示操作必须显示Brass Plus账户的其他信息
假设将第一个类命名为Brass,第二个类为BrassPlus。
开发Brass类和Brass Plus类
如果要在派生类中重新定义基类的方法,通常应将基类方法声明为虚的,这样,程序将根据对象类型而不是引用或者指针的类型来选择方法版本。为基类声明一个虚析构函数也是一种惯例。
- brass.h
//brass.h--bank account classes
#ifndef BRASS_H_
#define BRASS_H_
#include <string>
//Brass Account Class
class Brass
{
private:
std::string fullName;
long acctNum;
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);
double Balance() const;
virtual void ViewAcct() const;
virtual ~Brass() {}
};
//Brass Plus Account Class
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 ResetOwes() {owesBank = 0;}
};
#endif // BRASS_H_
- brass.cpp
//brass.cpp---bank account class methods
#include <iostream>
#include "brass.h"
using namespace std;
//formatting stuff
typedef std::ios_base::fmtflags format;
typedef std::streamsize precis;
format setFormat();
void restore(format f, precis p);
//Brass methods
Brass::Brass(const string &fullName, long acctNum, double balance)
{
this->fullName = fullName;
this->acctNum = acctNum;
this->balance = balance;
}
void Brass::Deposit(double amt)
{
if (amt < 0)
cout << "Negative deposit not allowed; "
<< "deposit is canceled.\n";
else
balance += amt;
}
void Brass::Withdraw(double amt)
{
//set up ###.## format
format initialState = setFormat();
precis prec = cout.precision(2);
if (amt < 0)
cout << "Withdraw amount must be positive; "
<< "withdraw canceled.\n";
else if (amt <= balance)
balance -= amt;
else
cout << "Withdraw amount of $" << amt
<< " exceeds your balance.\n"
<< "Withdraw canceled.\n";
restore(initialState, prec);
}
double Brass::Balance() const
{
return balance;
}
void Brass::ViewAcct() const
{
//set up ###.## format
format initialState = setFormat();
precis prec = cout.precision(2);
cout << "Client: " << fullName << endl;
cout << "Account Number: " << acctNum << endl;
cout << "Balance: $" << balance << endl;
restore(initialState, prec);
}
//BrassPlus Methods
BrassPlus::BrassPlus(const string &fullName, long acctNum, double balance, double ml, double r)
: Brass(fullName, acctNum, balance)
{
this->maxLoan = ml;
this->rate = r;
this->owesBank = 0.0;
}
//BrassPlus Methods
BrassPlus::BrassPlus(const Brass &ba, double ml, double r)
: Brass(ba) //using implicate copy constructor
{
this->maxLoan = ml;
this->rate = r;
this->owesBank = 0.0;
}
//redefine how ViewAcct() works
void BrassPlus::ViewAcct() const
{
//set up ###.## format
format initialState = setFormat();
precis prec = cout.precision(2);
Brass::ViewAcct();
cout << "Maximum loan: $" << maxLoan << endl;
cout << "Owed to bank: $" << owesBank << endl;
cout.precision(3);
cout << "Loan Rate: $" << 100 * rate << "%\n";
restore(initialState, prec);
}
//redefine how Withdraw() works
void BrassPlus::Withdraw(double amt)
{
//set up ###.## format
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: $" << advance << endl;
cout << "Finance charge: $" << advance * rate << endl;
Deposit(advance);
Brass::Withdraw(amt);
}
else
cout << "Credit limit exceeded. Transaction canceled.\n $";
restore(initialState, prec);
}
format setFormat()
{
return cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
}
void restore(format f, precis p)
{
cout.setf(f, std::ios_base::floatfield);
cout.precision(p);
}
- usebrass1.cpp
//usebrass1.cpp ---testing bank account classes
#include <iostream>
#include "brass.h"
using namespace std;
int main()
{
Brass Piggy("Porcelot pigg", 381299, 4000.00);
BrassPlus Hoggy("Horatio Hogg", 382288, 3000.00);
Piggy.ViewAcct();
cout << endl;
Hoggy.ViewAcct();
cout << endl;
cout << "Depositing $1000 into the hogg Account.\n";
Hoggy.Deposit(1000.00);
cout << "New Balance: $" << Hoggy.Balance() << endl;
cout << "Withdrawing $4200 from the Pigg Account.\n";
Piggy.Withdraw(4200.00);
cout << "Pigg account Balance: $" << Piggy.Balance() << endl;
cout << "Withdrawing $4200 from the Hogg Account.\n";
Hoggy.Withdraw(4200.00);
Hoggy.ViewAcct();
return 0;
}
Loan Rate: $11.125%
Depositing $1000 into the hogg Account.
New Balance: $4000
Withdrawing $4200 from the Pigg Account.
Withdraw amount of $4200.00 exceeds your balance.
Withdraw canceled.
Pigg account Balance: $4000
Withdrawing $4200 from the Hogg Account.
Bank advance: $200.00
Finance charge: $22.25
Client: Horatio Hogg
Account Number: 382288
Balance: $0.00
Maximum loan: $500.00
Owed to bank: $222.25
Loan Rate: $11.125%
- usebrass2.cpp
//usebrass2.cpp ---polymorphic example
#include <iostream>
#include "brass.h"
using namespace std;
const int CLIENTS = 4;
int main()
{
Brass * p_clients[CLIENTS];
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 "
<< "Enter 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 fraction: ";
cin >> trate;
p_clients[i] = new BrassPlus(temp, tempnum, tempbal, tmax, trate);
}
while (cin.get() != '\n')
continue;
}
cout << endl;
for (int i = 0; i < CLIENTS; i++)
{
p_clients[i]->ViewAcct();
cout << endl;
}
for (int i = 0; i < CLIENTS; i++)
{
delete p_clients[i];
}
cout << "Done.\n";
return 0;
}
Enter client's name: Harry Fishsong
Enter client's account number: 112233
Enter opening balance: $150
Enter 1 for Brass Account or Enter 2 for BrassPlus Account: 1
Enter client's name: Dinah Otternoe
Enter client's account number: 121213
Enter opening balance: $1800
Enter 1 for Brass Account or Enter 2 for BrassPlus Account: 2
Enter the overdraft limit: $350
Enter the interest rate as a decimal fraction: 0.12
Enter client's name: Brenda Birdherd
Enter client's account number: 212118
Enter opening balance: $5200
Enter 1 for Brass Account or Enter 2 for BrassPlus Account: 2
Enter the overdraft limit: $800
Enter the interest rate as a decimal fraction: 0.10
Enter client's name: Tim Turtletop
Enter client's account number: 233255
Enter opening balance: $688
Enter 1 for Brass Account or Enter 2 for BrassPlus Account: 1
Client: Harry Fishsong
Account Number: 112233
Balance: $150.00
Client: Dinah Otternoe
Account Number: 121213
Balance: $1800.00
Maximum loan: $350.00
Owed to bank: $0.00
Loan Rate: $12.000%
Client: Brenda Birdherd
Account Number: 212118
Balance: $5200.00
Maximum loan: $800.00
Owed to bank: $0.00
Loan Rate: $10.000%
Client: Tim Turtletop
Account Number: 233255
Balance: $688.00
Done.