我正在尝试从支票和储蓄帐户中打印余额。我知道您无法使用void函数返回值,但是我可以用哪种方式显示两个帐户的余额?
#ifndef ACCOUNT_H
#define ACCOUNT_H
// Account.h
// 4/8/14
// description
class Account {
private:
double balance;
double interest_rate; // for example, interest_rate = 6 means 6%
public:
Account();
Account(double);
void deposit(double);
bool withdraw(double); // returns true if there was 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
我在void Bank :: print_balances()下遇到2个错误。它只是说:
"no match for 'operator<<' in 'std::cout << ((Bank*)this) ->Bank::savings'"
我已经阅读了很多,但是我所学到的是因为“支票”和“储蓄”是一种帐户类型,因此无法使用。我以前的项目与此类似,而我使用了“双精度”类型,因此我能够返回一个值。
抱歉,如果格式错误。首次在此网站上发布。
最佳答案
您需要为自定义类operator<<
重载Account
以便能够cout<<
其对象。
class Account {
...
public:
friend ostream& operator<<(ostream &os, const Account &dt);
...
};
ostream& operator<<(ostream &os, const Account &dt)
{
os << dt.balance; // print its balance
return os;
}
要继续阅读,请签出Overloading the I/O operators。