如何使用派生成员函数修改基类中的私有变量?

时间:2015-05-31 16:17:48

标签: c++ inheritance

我的完整问题是因为我无法完全适应标题:如何2使用派生类B成员函数修改基类中的私有变量,该函数将调用已在基类A中重写的成员函数这也将修改派生类B中的不同私有成员变量。我正在努力解决这个问题,因为我无法弄清楚如何修改两个成员中不同类中的两个私有成员变量来自不同类的函数。到目前为止,这就是我的代码。我将在代码中对我正在尝试解决的问题进行评论

在我的.h档案中,我有:

#include <iostream>
#include <string>
using namespace std;

class A{
public:
    A();
    A(string name_holder, double balance_holder);
    int take(float amount);
    string getName();
    double getBalance();
    void output();
private:
    string name;
    double balance;
};

class B:public A{
public:
    B();
    B(int number_of_withdrawal_holder);
    int take(float amount);//overriding
    void output();
private:
    static int count;
};

在我的.cpp文件中我有

#include "Header.h"


A::A()
{
    name=" ";
    balance=0;
}

A::A(string name_holder,double balance_holder)
{
    name=name_holder;
    balance=balance_holder;
}
int A::take(float amount)
{
    if (balance >= amount && amount>=0)//if the amount is less than or equal to the balance and is nonnegative
    {
        balance-=amount;
        cout<<"ok"<<endl;
        return 0;
    }

    cout <<"Insufficient funds for the withdrawal to take place"<<endl;
    return 1;

}

string A::getName()
{
    return name;
}
double A::getBalance()
{
    return balance;
}

void A::output()
{
    cout<<"Name: "<<getName()<<endl;
    cout<<"Balance: "<<getBalance()<<endl;
}

int B::count=0;

B::B()
{
    count=0;
}
B::B(int number_of_withdrawal_holder)
{
    count=number_of_withdrawal_holder;
}
int B::take(float amount)
{
    if(count==0)//if this is the first withdrawal
    {
        ++count;
        return BankAccount::take(amount);
    }

    //the bottom part of the code gets excuted if you already withdrew atleast once-you pay a fee of 1.50(in other words i want to do a function call to the first withdraw function and subtract 1.50 from the member variable balance but I also want to modify count in the base class function take

    ++number_of_withdrawals;

    return BankAccount::withdraw(amount);
}

如果有人能帮助我,那就太棒了!

2 个答案:

答案 0 :(得分:1)

即使是派生的子类,private成员也是私有的。如果要允许派生的子类访问成员,请将其设为protected而不是private。这些成员仍然不公开,但可以通过子类访问。

答案 1 :(得分:0)

转到答案:

我认为你做错了..你的基类是一个帐户,为你提供指定帐户交易的界面,所以你不应该修改基类的任何内部,而不是修改公众提供的内容。界面,所以你的“费用”也是退出操作..

正如评论中真正提到的,A :: take()应该被声明为虚拟

class A {
  ...
    virtual int take(float amount);
  ...
}
class B: public A {

    B() {
        m_nNumberOfWithdraw = 0;
    }

    B::B(int number_of_withdrawal_holder) {
        m_nNumberOfWithdraw =number_of_withdrawal_holder;
    }

    int B::take(float amount) {

          int nResult = A::take(m_nNumberOfWithdraw > 0 ? amount + 1.50 :amount);

          if (nResult == 0)
               m_nNumberOfWithdraw++;

          return nResult;
    }


    protected:

        int      m_nNumberOfWithdraw;
};