[英]C++ Inheritance accessing a non-virtual function in derived class from base class pointer
Consider the following code for 考虑以下代码
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";};
};
I want to call setIntrestEarned()
in SavingAccount class with base class pointer. 我想使用基类指针在SavingAccount类中调用
setIntrestEarned()
。 I don't want to add setIntrestEarned()
as virtual
in base class BankAccount because it has no meaning in the other type of accounts like derived one CurrentAccount . 我不想在基类BankAccount中将
setIntrestEarned()
添加为virtual
,因为它在其他类型的帐户(如派生的CurrentAccount)中没有意义。
And if we keep adding various function in different derived class as virtual in base class then it will end up like a superset of functions of derived class. 而且,如果我们继续在不同的派生类中添加各种函数作为基类中的虚函数,那么它将最终像派生类的函数的超集一样结束。
What would be the best way to design these type of class hierarchy? 设计这些类型的类层次结构的最佳方法是什么?
If it has no meaning in your base class, then you do not need to inherit from it. 如果它在您的基类中没有意义,那么您不需要继承它。
Inheritance is only useful in the form where: B is a subset of A. B can have exclusive functions that A does not have. 继承仅在以下形式中有用:B是A的子集。B可以具有A没有的排他功能。
Hence, if your savingsacc class requires certain information that A contains, then inherit it, and create exclusive functions for B that A does not need as C may also be a subset of A. 因此,如果您的Savingsacc类需要A包含的某些信息,则继承它,并为B创建A不需要的排他函数,因为C可能也是A的子集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.