我在C++中學習了一個類,並且遇到了問題。我們必須創建一個銀行帳戶列表,每個銀行帳戶都有自己的儲蓄和支票帳戶。我來得相當遠,但現在我不得不使用「ofstream & fout」來打印檢查和儲蓄想象力帳戶。如何在繼承中使用'fout'
的「Account.h」我的頭文件看起來像這樣(我認爲這是正確的):
#include <iostream>
#include <cmath>
#include <fstream>
#ifndef ACCOUNT_H
#define ACCOUNT_H
using namespace std;
class Account{
protected:
string number;
double balance;
public:
Account(){}
Account(string nr, double bl);
void deposit(double am);
string get_number();
double get_balance();
double withdraw(double am);
bool equals(Account other);
virtual void print();
void println();
void println(string s);
virtual void println(ofstream& fout);
virtual void read(ifstream& fin);
};
#endif
我的定義文件是在這一切發生可怕的事情與fstream的部分:
#include "Account.h"
Account::Account(string nr, double bl){
if (bl >= 0){
number = nr;
balance = bl;
}
else{
number = "incorrect";
}
}
void Account::deposit(double am){
if (am >= 0){
balance = balance + am;
}
}
string Account::get_number(){
return number;
}
double Account::get_balance(){
return balance;
}
double Account::withdraw(double am){
if (0 <= am && am <= get_balance()){
balance = balance - am;
return am;
}
else{
return 0;
}
}
bool Account::equals(Account other){
if (number == other.get_number()){
return true;
}
return false;
}
void Account::print(){
cout << "<Account(" << number << ",";
cout << balance << ")>" ;
}
void Account::println(){
print();
cout << endl;
}
void Account::println(string s){
cout << s;
println();
}
void Account::println(ofstream& fout){
fout << number << ",";
fout << balance;
fout << endl;
}
void Account::read(ifstream& fin){
fin >> number;
}
void Account :: println(ofstream & fout)的聲明有問題。它給我的輸出
<Account(number,balance,0)>
代替
<Account(number,balance)>
爲什麼會出現這種情況?我在印刷儲蓄和檢查號碼方面遇到了更多問題,但我覺得如果我明白爲什麼會發生這種情況,我可以解決這些問題。感謝任何想幫助我的人。
我知道我有太多的打印方法,但是這是所有的分配。我必須這樣做,並使用正常的println(),餘額也是雙倍。雖然「,0」不出現在那裏。 我知道有一種方法可以像fstream那樣做,我只是不知道如何。 –
考慮打印'static_cast(平衡)'而不是(或者更好的是,使用'std :: setprecision(3)'或類似的)。 std :: cout和std :: ofstream實例可能默認使用不同的格式標誌。 –
utnapistim