C++继承从基类指针访问派生类中的非虚拟函数

C++ Inheritance accessing a non-virtual function in derived class from base class pointer

本文关键字:虚拟 函数 派生 继承 基类 指针 访问 C++      更新时间:2023-10-16

考虑的以下代码

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如果我们继续在不同的派生类中添加各种函数作为基类中的虚函数,那么它最终会像派生类的函数的超集一样。

设计这些类型的类层次结构的最佳方法是什么?

如果它在基类中没有意义,那么您不需要从它继承。

继承仅在以下形式中有用:B是a的子集。B可以具有A所没有的排他函数。

因此,如果您的savingsacc类需要A包含的某些信息,那么继承它,并为B创建A不需要的独占函数,因为C也可能是A的子集。