更新对象的属性时遇到问题?

Having trouble updating an object's attributes?

我有一个名为 Update Account 的虚拟方法,其中基于从 find 方法找到并返回到 main 的指针,帐户将相应地更新。

有一个名为 Account 的父级 class,其中 Savings 派生自。

但是储蓄不会输出更新后的利息,不会让利息生效

所有账户都是有余额的,存款不会在账户之间变化,所以我调用了账户的存款方法

void Savings::UpdateAccount(Date *date)
{
     int   interestMonths;
     short lastYear;
     short lastMonth;
     float currBal;

     //THESE GET THE CURRENT DATE - Differs from the account creation
     //date and allows for the calculation of interest

     lastMonth = GetAccountMonth();
     lastYear  = GetAccountYear();
     currBal   =  GetAccountBal();

        if (((date -> GetYear ( ) - lastYear) * 12 +
           (date -> GetMonth ( ) - lastMonth )) > 0)
        {
            interestMonths = ((date -> GetYear ( ) - lastYear) * 12 +
                             (date -> GetMonth ( ) - lastMonth));

            for (int index = 0; index < interestMonths; index++)
            {
                currBal = currBal + (currBal * interestRate);
            }

           //This method takes the calculated current balance, then
           //passes it into the parent class method to update the 
           //private accountBal attribute. 

           SetBalance(currBal);
        }
}

问题是此方法没有更新对象的余额,我很确定我的利率计算不是问题。

感谢您的帮助 - 此方法现在有效。

您正在更新 a 余额,但帐户错误。

void Savings::UpdateAccount(Date *date)const
{
     int   interestMonths;
     short lastYear;
     short lastMonth;
     float currBal;
     Account myAccount;

这里,myAccount是一个局部变量,与您刚刚找到的帐户无关(即this)...

 myAccount.SetBalance(currBal);

...您正在更新的是该帐户的余额。

您想修改调用函数的对象,所以只需说

SetBalance(currBal);

并从函数中删除 const — 您不能拥有更新帐户但不修改帐户的函数。

您也不需要在 Savings 成员的定义中添加 "Savings::" —

 lastMonth = GetAccountMonth();
 lastYear = GetAccountYear();
 currBal = GetAccountBal();

应该可以正常工作。