我在一个名为bankAccount的基类中有一个名为balance的私有数据成员。我希望我的派生类checkingAccount能够使用平衡,所以我保护它但我注意到我的派生类似乎仍然能够访问平衡,即使它被放在我的基类的私有部分。我以为这不可能?有谁知道会发生什么事?
基类:
class bankAccount
{
public:
bankAccount();
void setAccountInfo(int accountNumTemp, double balanceTemp);
void applyTransaction(char accountType, char transactionTypeTemp, int amountTemp, int j);
private:
int accountNumber;
double balance;
};
派生类:
class checkingAccount: public bankAccount
{
public:
checkingAccount();
double applyTransaction(char transactionTypeTemp, int amountTemp, int c, double balance);
private:
float interestRate;
int minimumBalance;
float serviceCharge;
};
基类函数成员,派生类函数成员收到有问题的数据库:
void bankAccount:: applyTransaction(char accountType, char transactionTypeTemp, int amountTemp, int j)
{
int c;
c = j;
checkingAccount ca;
balance = ca.applyTransaction(transactionTypeTemp, amountTemp, c, balance);
}
派生类函数成员,其中使用了基类的私有数据成员:
double checkingAccount:: applyTransaction(char transactionTypeTemp, int amountTemp, int c, double balance)
{
if (transactionTypeTemp == 'D')
{
balance = balance + amountTemp;
}
else if (transactionTypeTemp == 'W')
{
if (balance < amountTemp)
{
cout << "error: transaction number " << c + 1 << " never occured due to insufficent funds." << endl;
}
else
{
balance = balance - amountTemp;
if(balance < minimumBalance) //if last transaction brought the balance below minimum balance
{
balance = (balance - serviceCharge); //apply service charge
}
}
}
return balance;
}
答案 0 :(得分:2)
balance
是函数的第四个参数(checkingAccount:: applyTransaction
);它不是bankAccount
的数据成员。
答案 1 :(得分:2)
checkingAccount::applyTransaction
没有看到或触及基类的balance
成员。它正在使用,重置并返回自己的balance
参数。