gpt4 book ai didi

c++ - 使自定义类 ostream 可输出?

转载 作者:太空宇宙 更新时间:2023-11-04 15:03:35 26 4
gpt4 key购买 nike

我正在尝试打印支票和储蓄账户的余额。我知道您不能使用 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<<为您的自定义类(class) 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 .

关于c++ - 使自定义类 ostream 可输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23063838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com