0

c++ question about operator overload.What's wrong exactly??

The given code declares an Account class which has a balance and interest members. The bank asks you to add a new functionality to merge two accounts together, resulting in a new account with the sum of the balances and interests of the given accounts. Overload the + operator to allow adding two Account objects, adding the balances and interests. The overloaded operator should return a new Account object, with the corresponding member values. this is my code: #include <iostream> using namespace std; class Account { private: int balance=0; int interest=0; public: Account() {} Account(int a): balance(a) { interest += balance/10; } int getTotal() { return balance+interest; } //your code goes here Account operator+(Account &obj){ Account res; res.getTotal = this ->getTotal+obj.getTotal; return res; } }; int main() { int n1, n2; cin >> n1 >> n2; Account a(n1); Account b(n2); Account res = a+b; cout << res.getTotal(); }

3rd Mar 2021, 10:55 PM
micro
micro - avatar
5 Answers
+ 2
#include <iostream> using namespace std; class Account { private: int balance=0; int interest=0; public: Account() {} Account(int a): balance(a) { interest += balance/10; } int getTotal() { return balance+interest; } //your code goes here // Account operator+(Account &obj){ Account res; res.balance = this->balance+obj.balance + this->interest+obj.interest; return res; } }; int main() { int n1, n2; cin >> n1 >> n2; Account a(n1); Account b(n2); Account res = a+b; cout << res.getTotal(); }
18th Dec 2021, 9:52 PM
Brian H
Brian H - avatar
+ 2
#include <iostream> using namespace std; class Account { private: int balance=0; int interest=0; public: Account() {} Account(int a): balance(a) { interest += balance/10; } int getTotal() { return balance+interest; } //your code goes here Account operator+(Account &obj) { Account res(this->balance+obj.balance); return res; } }; int main() { int n1, n2; cin >> n1 >> n2; Account a(n1); Account b(n2); Account res = a+b; cout << res.getTotal(); } Good Luck
25th Jan 2022, 6:11 PM
Muhammad Alif Deva Rizqon
Muhammad Alif Deva Rizqon - avatar
+ 1
Nm, i did it thx a lot CarrieForle
3rd Mar 2021, 11:45 PM
micro
micro - avatar
0
getTotal() is a method, not a field (member variable), so it doesn't work. You should add the 2 fields separately.
3rd Mar 2021, 11:37 PM
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ
ä½ ēŸ„é“č¦å‰‡ļ¼Œęˆ‘也ę˜Æ - avatar
0
How?
28th Nov 2021, 6:43 AM
Danjhay Lunzaga
Danjhay Lunzaga - avatar