我不想在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’
如何修復代碼?
注意,如果*是*聲明爲const引用,初始化是合法的(至少對於與結合臨時的),但是'test'實例將持有對在構造函數執行結束時被銷燬的臨時對象的引用。 – 2012-02-26 05:52:31
在這種情況下,我如何聲明作爲一個對象? – 2012-02-26 05:54:35
@AndréCaron:換句話說,將'ofs'聲明爲const引用不是一個解決方案。 – Nawaz 2012-02-26 05:54:40