我有一个类 (SavingAccount) 继承自另一个类 (Account)。不知何故,它没有正确初始化。
============================================= =========================
class Account
{
private:
double balance;
public:
// constructor
Account()
{
balance = 0;
}
Account(double b)
{
if (b >= 0)
balance = b;
else
{
balance = 0;
cout << "Balance cannot be negative." << endl;
}
}
// destructor
~Account()
{
// nothing
}
// required functions
bool credit(double a)
{
if (a > 0)
{
balance += a;
return true;
}
else
{
cout << "Credit amount must be greater than 0." << endl;
return false;
}
}
bool debit(double a)
{
if (a > 0 && a <= balance)
{
balance -= a;
return true;
}
else if (a > balance)
{
cout << "Debit amount exceeded account balance." << endl;
return false;
}
}
double getBalance()
{
return balance;
}
void setBalance(double b)
{
balance = b;
}
};
============================================= =========================
class SavingAccount : public Account
{
private:
double interestRate; // percentage
public:
// constructor
SavingAccount()
{
Account::Account();
interestRate = 0;
}
SavingAccount(double b, double r)
{
if (b >= 0 && r >= 0)
{
Account::Account(b);
interestRate = r;
}
else
{
Account::Account();
interestRate = 0;
cout << "Balance or rate cannot be negative." << endl;
}
}
// destructor
~SavingAccount()
{
// nothing
}
// required functions
double calculateInterest()
{
return Account::getBalance() * interestRate / 100;
}
};
============================================= =========================
我初始化如下:
SavingAccount acctSaving(2000, 5);
当我跳进去时,acctSaving 显示其余额为 2000。然而,当它到外面时,余额又回到了 0。
如果我改变这一行:
Account::Account(b);
进入:
setBalance(b);
它正确地返回了余额值为 2000 的对象。出了什么问题?第一种方法怎么不对?
最佳答案
Account::Account(b)
并不像您认为的那样。它创建一个类型为 Account
的未命名临时变量,用 b
初始化,然后立即销毁。
您可能正在寻找的是这样的东西:
SavingAccount(double b, double r)
: Account(b >= 0 && r >= 0 ? b : 0) {
/* rest of code here */
}
关于C++ 继承类未正确初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848492/