【问题标题】:How is this private data member of a base class being accessed by a derived class?派生类如何访问基类的这个私有数据成员?
【发布时间】:2011-08-16 05:06:50
【问题描述】:

我在名为 bankAccount 的基类中有一个名为 balance 的私有数据成员。我希望我的派生类检查帐户能够使用余额,所以我将其设为受保护,但我注意到我的派生类似乎仍然能够访问余额,即使它被放在我的基类的私有部分中。我以为这是不可能的?有谁知道发生了什么?

基类:

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

【问题讨论】:

  • 不要从没有虚拟析构函数的基类派生。请。
  • 哦,请不要在实际应用程序中将财务数据存储为浮点值。舍入误差肯定会蒸发或创造金钱。

标签: c++ class inheritance


【解决方案1】:

balance 在该上下文中是函数的第四个参数 (checkingAccount:: applyTransaction);它不是bankAccount 的数据成员。

【讨论】:

  • 这也是我最初的想法,但是,我的输出表明派生函数中执行了一些操作的 balance 的值与基类 balance 的值相同
  • @Matt 您在完成 applyTransaction 后正在更新私有成员变量 balance,所以一旦结束,它当然会是一样的。您是说它在 applyTransaction 期间发生变化吗?
  • 我说新余额的价值与旧余额的价值相同。如果未初始化,新余额的值不应该是内存中的值吗?
【解决方案2】:

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

【讨论】:

  • 这也是我最初的想法,但是,我的输出表明派生函数中执行了一些操作的 balance 的值与基类 balance 的值相同
  • @Matt:您在哪里通过指向bankAccount 的指针/引用在checkingAccount 上调用applyTransaction
  • 所以我想问题是,新余额如何获得旧余额的价值?
  • @Matt:请回答我的问题,因为如果您按照我的描述进行操作,解决方案很简单。
  • 嗯,不确定。我在 main 中调用 bankAccounts applytransaction,然后在 bankAccounts 内部应用事务,调用了 checksAccounts applyTransaction。
猜你喜欢
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-30
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多