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

标签 c++ class inheritance

我在名为 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/

相关文章:

c++ - 尝试模拟 SystemC 文件时出现 "multiple definition of"消息

c++ - 使用固定内核进行多次迭代的膨胀/腐 eclipse 是否类似于具有更大尺寸的等效内核的膨胀/腐 eclipse

python - 散列 Python 类是个好主意吗?

java - 是否可以在不创建实例的情况下检查一个类是否在java中扩展另一个类?

c++ - 容器类和继承调用虚方法

c++ - 通过不同的父类从同一个基类进行多重继承真的是个问题吗?

c++ - Std::vector 不更改类内的数据

c# - 动态更改对象的命名空间

c++ - 循环包含

c - memcpy 类似继承的结构 - 安全吗?