【问题标题】:C++ Inheritance accessing a non-virtual function in derived class from base class pointerC++继承从基类指针访问派生类中的非虚函数
【发布时间】: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-castingdown-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


【解决方案1】:

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

继承仅在以下形式中有用: B 是 A 的子集。 B 可以拥有 A 没有的独占功能。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    相关资源
    最近更新 更多