C++继承从基类指针访问派生类中的非虚拟函数
C++ Inheritance accessing a non-virtual function in derived class from base class pointer
考虑的以下代码
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类中的 CurrentAccount如果我们继续在不同的派生类中添加各种函数作为基类中的虚函数,那么它最终会像派生类的函数的超集一样。 设计这些类型的类层次结构的最佳方法是什么?setIntrestEarned()
。我不想在基类BankAccount中将setIntrestEarned()
添加为virtual
,因为它在其他类型的帐户中没有意义,比如派生帐户
如果它在基类中没有意义,那么您不需要从它继承。
继承仅在以下形式中有用:B是a的子集。B可以具有A所没有的排他函数。
因此,如果您的savingsacc类需要A包含的某些信息,那么继承它,并为B创建A不需要的独占函数,因为C也可能是A的子集。
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 用纯虚拟函数兜圈子
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 禁止子函数调用父级的抽象(或虚拟)函数
- 无法在子类中使用虚拟函数C++
- 无法在派生对象上运行虚拟函数
- 我可以调用从 main() 覆盖的虚拟函数吗?
- 在 C++ 中将函数获取和设置为虚拟函数
- 使用在堆栈上创建的对象调用虚拟函数
- 为什么在这种情况下不调用我的虚拟函数实现?
- 在C++中使虚拟函数私有化
- 模板继承类中的虚拟函数
- 为什么构造函数的虚拟函数调用有时有效,但其他调用却无效
- doxygenc++虚拟函数和实现
- 如何从派生类函数中调用虚拟函数