2014-01-15 25 views
0

我在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)> 

爲什麼會出現這種情況?我在印刷儲蓄和檢查號碼方面遇到了更多問題,但我覺得如果我明白爲什麼會發生這種情況,我可以解決這些問題。感謝任何想幫助我的人。

回答

0

Account::println(ofstream&)將打印「」,但由於平衡了一倍,它與一個小數位打印:

如果平衡== 0.0,它將打印爲eiter 0.0或0.0,這取決於你語言環境。

無論哪種方式,你有太多的印刷方法,而且我覺得解決方案應該通過輸出操作來實現:

頁眉:

class Account { 
    // .... 
    // no print methods defined 
}; 
std::ostream& operator <<(std::ostream& out, const Account& a); 

來源: 的std :: ostream的&運營商< <(std :: ostream & out,const Account & a) { return < <「」; }

客戶端代碼:

#include <iostream> // console 
#include <fstream> // file 

Account a; 
// print to console 
std::cout << a << std::endl; 
// print to file 
std::ofstream fout("./account.txt"); 
fout << a << std::endl; 
+0

我知道我有太多的打印方法,但是這是所有的分配。我必須這樣做,並使用正常的println(),餘額也是雙倍。雖然「,0」不出現在那裏。 我知道有一種方法可以像fstream那樣做,我只是不知道如何。 –

+0

考慮打印'static_cast (平衡)'而不是(或者更好的是,使用'std :: setprecision(3)'或類似的)。 std :: cout和std :: ofstream實例可能默認使用不同的格式標誌。 – utnapistim