c++ - Overloaded Operator not working properly? -
i getting error when compile program , unsure how fix appropriate function solve problem. post main, header, , cpp file below desired outcome following. help/tips appreciated, thank you!
error get:
error c2679 binary '+=': no operator found takes right-hand operand of type 'double'
updated: have fixed code update "=" operator overload , working except 1 line of output.
this output:
a: no name: $0.00
b: saving: $10000.99
c: checking: $100.99
a: no name: $10101.98
b: saving: $10000.99
c: checking: $100.99
a: joint: $0.00
b: saving: $10000.99
c: checking: $100.99
a: saving: $10101.98
b: saving: $10101.98
c: checking: $100.99
a: saving: $10302.98
b: saving: $10302.98
c: checking: $201.00
for reason "joint" balance comes 0 , unsure why. should show $10101.98
the main:
#include <iostream> #include "account.h" using namespace std; void displayabc(const account& a, const account& b, const account& c) { cout << "a: " << << endl << "b: " << b << endl << "c: " << c << endl << "--------" << endl; } int main() { account a; account b("saving", 10000.99); account c("checking", 100.99); displayabc(a, b, c); = b + c; displayabc(a, b, c); = "joint"; displayabc(a, b, c); = b += c; displayabc(a, b, c); = b += c += 100.01; displayabc(a, b, c); return 0; }
source file:
#include <iomanip> #include <cstring> #include "account.h" using namespace std; account::account() { name_[0] = 0; balance_ = 0; } account::account(double balance) { name_[0] = 0; balance_ = balance; } account::account(const char name[], double balance) { strncpy(name_, name, 40); name_[40] = 0; balance_ = balance; } void account::display(bool gotonewline)const { cout << (name_[0] ? name_ : "no name") << ": $" << setprecision(2) << fixed << balance_; if (gotonewline) cout << endl; } account& account::operator+=(account& other) { balance_ += other.balance_; return *this; } account& account::operator=(const account& ls) { strcpy(name_, ls.name_); balance_ = ls.balance_; return *this; } account operator+(const account &one, const account &two) { return account(one.balance_ + two.balance_); } ostream& operator<<(ostream& os, const account& a) { a.display(); return os; }
header file:
#ifndef _account_h__ #define _account_h__ #include <iostream> class account { char name_[41]; double balance_; public: account(); account(double balance); account(const char name[], double balance = 0.0); void display(bool gotonewline = true)const; account& operator+=(account& other); account& operator=(const account & other); friend account operator+(const account &one, const account &two); }; std::ostream& operator<<(std::ostream& os, const account& a); }; #endif
change +=
operator method to:
account& operator+=(const account& other);
Comments
Post a Comment