2012-02-26 54 views
1

我不想在main()中構造ofstream。這是我做的,但它不能編譯:在類中初始化流

#include <fstream> 
using namespace std; 
class test 
{ 
private: 
    ofstream &ofs; 
public: 
    test(string FileName); 
    void save(const string &s); 
}; 
//---------------- 
test::test(string FileName) 
    : ofs(ofstream(FileName.c_str(),ios::out)) 
{ 
} 
//---------------- 
void test::save(const string &s) 
{ 
    ofs << s; 
} 
//---------------- 
//Provide file name and to-be-written string as arguments. 
int main(int argc,char **argv) 
{ 
    test *t=new test(argv[0]); 
    t->save(argv[1]); 
    delete t; 
} 

test.cpp: In constructor ‘test::test(std::string)’: 
test.cpp:13: error: invalid initialization of non-const reference of type ‘std::ofstream&’ from a temporary of type ‘std::ofstream’ 

如何修復代碼?

回答

4

表達式ofstream(FileName.c_str(),ios::out))創建了一個不能綁定到非const引用的臨時對象。

你爲什麼不這樣做,而不是(閱讀評論,以及):

class test 
{ 
private: 
    ofstream ofs; //remove & ; i.e delare it as an object 
public: 
    test(string const & FileName); //its better you make it const reference 
    void save(const string &s); 
}; 

test::test(string const & FileName) //modify the parameter here as well 
    : ofs(FileName.c_str(),ios::out) //construct the object 
{ 

} 

希望有所幫助。

+1

注意,如果*是*聲明爲const引用,初始化是合法的(至少對於與結合臨時的),但是'test'實例將持有對在構造函數執行結束時被銷燬的臨時對象的引用。 – 2012-02-26 05:52:31

+0

在這種情況下,我如何聲明作爲一個對象? – 2012-02-26 05:54:35

+0

@AndréCaron:換句話說,將'ofs'聲明爲const引用不是一個解決方案。 – Nawaz 2012-02-26 05:54:40

0

只有在特殊情況下,您將對另一個對象的引用用作類數據成員。通常你想在成員對象上使用類的生命期依賴。通常,你的班級在複製和分配方面受到限制。如果您確實需要參考,則該對象必須已創建。

來電:

ofstream ouf("someFileName.txt"); 
test testObj(ouf) 

你的類的頭:

test::test(ofstream& ous) : ofs(ous) { }