2013-02-11 36 views
1

如何使一個ofstream參數可選?C++中可選的流參數

bool LookingFor(std::string &mi_name, ofstream &my_file = std::cout) 
{ 
    my_file << xxx; 
....... 

} 

用上述方法簽名的編譯錯誤是:

'的std :: ofstream的& my_file' 具有輸入 '的std :: ostream的{又名的std :: basic_ostream}'

I」 m使用mingw32。

我想要這個函數在沒有第二個參數時寫入控制檯。 我嘗試了無數的東西,但沒有任何工作。 如果我要檢查代碼,看它是否是開放的,比如我不介意:

if(my_file.isopen()) 
    my_file << xxx; 
else 
    cout << xxx; 

什麼好主意?

回答

3

只需使用ostream

bool LookingFor(std::string &mi_name, std::ostream &out = std::cout) { 
    out << xxx; 
} 

這將與任何流類型的工作,不僅fstream,也cout。和其他流類型,如ostringstream