繁体   English   中英

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类中调用setIntrestEarned() 我不想在基类BankAccount中将setIntrestEarned()添加为virtual ,因为它在其他类型的帐户(如派生的CurrentAccount)中没有意义。

而且,如果我们继续在不同的派生类中添加各种函数作为基类中的虚函数,那么它将最终像派生类的函数的超集一样结束。

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM