【发布时间】:2018-07-23 06:43:47
【问题描述】:
考虑以下代码
class BankAccount
{
protected:
int accNo;
int balance;
std::string custName;
std::string custAddress;
public:
BankAccount(int aNo, int bal, std::string name, std::string address);//:accNo(aNo), balance(bal), custName(name), custAddress(address);
BankAccount(const BankAccount&);
BankAccount();
~BankAccount();
BankAccount& operator=(const BankAccount&);
int getAccNumber() const {return accNo;};
virtual int getBalance() const {return balance;};
std::string getAccountHolderName()const {return custName;};
std::string getAccountHolderAddress()const {return custAddress;};
virtual std::string getAccountType()const{return "UNKNOWN";};
};
class CurrentAccount:public BankAccount
{
private:
int dailyTrancLimit;
public:
CurrentAccount(int aNo, int bal, std::string name, std::string address);
int getTransactionLimit()const {return dailyTrancLimit;};
void setTranscationLimit(int transLimit){dailyTrancLimit = transLimit;};
std::string getAccountType()const{return "CURRENT";};
};
class SavingAccount:public BankAccount
{
private:
int intrestRate;
int accumuatedIntrest;
public:
SavingAccount(int aNo, int bal, std::string name, std::string address);
int getBalance()const {return balance+accumuatedIntrest;};
void setIntrestEarned(int intrest){accumuatedIntrest=intrest;};
std::string getAccountType()const{return "SAVINGS";};
};
我想用基类指针在 SavingAccount 类中调用setIntrestEarned()。我不想在基类 BankAccount 中将 setIntrestEarned() 添加为 virtual,因为它在派生帐户 CurrentAccount 等其他类型的帐户中没有任何意义。 p>
如果我们继续在不同的派生类中添加各种函数作为基类中的虚拟函数,那么它最终将成为派生类函数的超集。
设计这些类型的类层次结构的最佳方法是什么?
【问题讨论】:
-
做一些关于up-casting和down-casting的研究。
-
如果你知道
Base类的对象肯定是Derived类的实例(如果你想可靠地调用派生的方法,你必须知道类),然后您可以将它们强制转换为派生类以调用它。 -
@ Zinki 考虑以下内容: void printAccDetails(BankAccount* const acc) { coutgetAccountHolderName()getBalance()getAccountType(); //coutgetTransactionLimit(); //Error here } 现在我想用指针的差异类型(Current、Savings 和 bankAcc)调用这个函数。所以在这个函数中,我必须确定 acc 的类型和打印它的详细信息。我这里怎么确定???考虑没有函数 getAccountType();
-
没有自动投射。当且仅当您确定
p指向的对象是T类型时,您才能使用static_cast<T*>(p)。如果指向的对象不是T类,dynamic_cast<T*>将返回nullptr。
标签: c++ inheritance