c++ - Making a custom class ostream outputable? -
i'm trying print balance checking , savings account. know can't return value using void function, in way can show balances both accounts?
#ifndef account_h #define account_h // account.h // 4/8/14 // description class account { private: double balance; double interest_rate; // example, interest_rate = 6 means 6% public: account(); account(double); void deposit(double); bool withdraw(double); // returns true if there enough money, otherwise false double query(); void set_interest_rate(double rate); double get_interest_rate(); void add_interest(); }; #endif // bank.cpp // 4/12/14 // description #include <iostream> #include <string> #include "bank.h" using namespace std; bank::bank(): checking(0), savings(0) { } bank::bank(double checking_amount, double savings_amount): checking(checking_amount), savings(savings_amount){; checking = account(checking_amount); savings = account(savings_amount); } void bank::deposit(double amount, string account) { if (account == "s") { savings.deposit(amount); } if (account == "c") { checking.deposit(amount); } } void bank::withdraw(double amount, string account) { if (account == "s") { savings.withdraw(amount); } if (account == "c") { checking.withdraw(amount); } } void bank::transfer(double amount, string account) { if (account == "s") { savings.deposit(amount); checking.withdraw(amount); } if (account == "c") { checking.deposit(amount); savings.withdraw(amount); } } void bank::print_balances() { cout << savings << endl; cout << checking << endl; } #ifndef bank_h #define bank_h // bank.h // 4/12/14 // description #include <string> #include "account.h" using namespace std; class bank { private: account checking; account savings; public: bank(); bank(double savings_amount, double checking_amount); void deposit(double amount, string account); void withdraw(double amount, string account); void transfer(double amount, string account); void print_balances(); }; #endif
i'm getting 2 errors under void bank::print_balances(). says:
"no match 'operator<<' in 'std::cout << ((bank*)this) ->bank::savings'"
i reading lot it, learned since "checking" , "savings" account type, won't work. previous project similar, , had "double" types instead able return value.
sorry if format wrong. first time posting on site.
you need overload operator<<
custom class account
in order able cout<<
objects.
class account { ... public: friend ostream& operator<<(ostream &os, const account &dt); ... }; ostream& operator<<(ostream &os, const account &dt) { os << dt.balance; // print balance return os; }
to read on, check out overloading i/o operators.
Comments
Post a Comment