让基类的方法使用继承类的静态成员变量...可能?
Having a base class's method use inherited class's static member variable... possible?
基类:
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
(因此变量是静态的)。这是用于赋值操作的,我们希望在 APR
s中使用静态成员变量。
从我的研究和测试中,我似乎找不到任何方法来覆盖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;
}
相关文章:
- C++:是否可以使用非静态成员变量模板?
- 如何在复杂继承中访问静态成员变量
- 静态成员变量不会由 gettext 转换
- 为什么我不能像这样在静态成员函数中调用静态成员变量?
- C++ lambda - 捕获静态成员变量
- 多线程处理中的静态成员变量
- 纯标头库中静态成员变量的正确设置器和 getter
- 如何从具有专用化的类模板定义静态成员变量?
- 为什么可以在没有实例变量的情况下访问静态回调方法中的静态成员变量?
- 声明和定义类静态成员变量不会导致多重声明,这是为什么?
- 为什么不允许静态成员变量的初始化在类中,而允许静态静态成员的初始化
- 类中的静态成员变量和C++中的全局变量有什么区别?
- C++ 静态成员变量 - 文件之间的访问
- 如何在运行时使用静态成员函数初始化静态成员变量
- 模板类中嵌套类的C 静态成员变量
- 如何检查静态成员变量模板?
- 重载运算符和静态成员变量的行为
- 类的静态成员变量(受保护)的作用域
- gcc 和 clang 中 constexpr 静态成员变量的链接器错误
- dll 中静态成员变量的生存期