让基类的方法使用继承类的静态成员变量...可能?

Having a base class's method use inherited class's static member variable... possible?

本文关键字:静态成员 变量 可能 基类 方法 继承      更新时间:2023-10-16

基类:

class SavingsAccount
{
public:
    void AddInterest();  // add interest to balance based on APR (interest rate)
private:
    static double APR;
    double Balance;
}
class CheckingAccount: public SavingsAccount
{
private:
    static double APR;
}

为了简单,我省略了不相关的成员/方法等。

所以,这里的情况是:CheckingAccount应该和SavingsAccount一样,但是它应该有不同的APR(利率)。所有SavingsAccounts共享相同的APR和所有CheckingAccounts共享他们自己的APR(因此变量是静态的)。这是用于赋值操作的,我们希望在 APRs中使用静态成员变量。

从我的研究和测试中,我似乎找不到任何方法来覆盖CheckingAccount类中的AddInterest()方法,让它使用CheckingAccount::APR。如果是这种情况,那么SavingsAccount中的大多数方法将不得不被重写,因为许多人使用APR,这似乎扼杀了学习继承类的意义。

我错过了什么吗?

AddInterest()方法,参考:

SavingsAccount::AddInterest()
{
    double interest = (this->APR/100)/12 * this->getBalance();
    this->setBalance(this->getBalance() + interest);
}

编辑:我遇到的原始问题(在CheckingAccount重写APR之前)如下:

int main()
{
    SavingsAccount sav;
    CheckingAccount chk;
    sav.setAPR(0.2);
    chk.setAPR(0.1);
    cout << sav.getAPR() << endl;  // OUTPUTS "0.1"!!
    return 0;
}

修改CheckingAccount对象的APR修改SavingsAccount对象的APR !这对我来说很有意义,因为APR是静态的,但我不确定最好的解决方案是什么。

我建议使用不同的类层次结构:

class Account {};
class SavingsAccount : public Account {};
class CheckingAccount : public Account {};

,然后在Account中添加virtual成员函数:

virtual double getAPR() = 0;

,然后用getAPR()实现Account::AddInterest()

class Account
{
   public:
      virtual ~Account() {}
      // Add other functions as needed
      // ...
      void AddInterest()
      {
         // Implement using getAPR()
         double interest = (this->APR/100)/12 * this->getBalance();
         this->setBalance(this->getBalance() + interest);
      }
      virtual double getAPR() = 0;
   private:
      double Balance;
};
class SavingsAccount : public Account
{
   public:
      virtual double getAPR() { return APR; }
   private:
      static double APR;
}
class CheckingAccount : public Account
{
   public:
      virtual double getAPR() { return APR; }
   private:
      static double APR;
}