我有一個名爲bankAccount的基類中稱爲餘額的私有數據成員。我想我的派生類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;
}
**不要從沒有虛擬析構函數的基類派生**請。 – 2011-04-30 20:39:34
哦,請不要將財務數據作爲浮點值存儲在實際應用程序中。舍入誤差肯定會蒸發或創造金錢。 – 2011-04-30 20:50:44