2015-05-14 108 views
0

我有一個名爲更新帳戶的虛擬方法,其中基於從find方法找到的指針並返回到main,該帳戶將相應地更新。無法更新對象的屬性?

有一個叫做Account的父類,其中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); 
     } 
} 

的問題是,這種方法沒有更新的對象和我的平衡我相當確定我的利率計算不是問題。

謝謝你的幫助 - 這種方法現在可以工作。

+1

一般來說,你可以這樣做,是的。但是你發佈的代碼似乎不是你問題的根源,不管這些應該是什麼。 –

+0

那麼如果沒有找到帳戶會發生什麼?提示調用者將得到一個指針,它不可能知道是對還是錯,並嘗試對其進行解引用。 –

+0

@ lovestogame227你剛剛編輯了這個問題。請注意:這樣做會使所有過去的答案和評論顯得無關緊要。 – Cinch

回答

2

您正在更新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成員的定義裏面 -

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

應該只是罰款。

+0

試過,但想出這個錯誤:多個標記在該行 \t - 過客「常量儲蓄」作爲「本」的說法「無效帳戶::的setBalance(浮動)」 \t丟棄預選賽[-fpermissive] \t - 無效參數'候選人是:無效SetBalance(浮動)'編輯:我沒有完全讀你的評論,只是刪除了常量。謝謝你。 – lovestogame227

+1

@ lovestogame227從函數中刪除'const'。 – molbdnilo

+0

@molbdnilo:你應該更新你的答案。用'const'方法試圖修改對象會是不好的;-) –