gpt4 book ai didi

c++ - 派生类如何访问基类的私有(private)数据成员?

转载 作者:行者123 更新时间:2023-11-27 23:30:19 24 4
gpt4 key购买 nike

我在名为 bankAccount 的基类中有一个名为 balance 的私有(private)数据成员。我希望我的派生类 checkingAccount 能够使用余额,所以我将其保护起来,但我注意到我的派生类似乎仍然能够访问余额,即使它被放在我的基类的私有(private)部分中也是如此。我以为这不可能?有谁知道会发生什么?

基类:

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);
}

使用基类私有(private)数据成员的派生类函数成员:

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;
}

最佳答案

checkingAccount::applyTransaction 没有看到或接触基类的 balance 成员。它使用、重置并返回自己的 balance 参数。

关于c++ - 派生类如何访问基类的私有(private)数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5844471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com