在课堂上初始化流

Mas*_*Liu 1 c++

我不想在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’
Run Code Online (Sandbox Code Playgroud)

如何修复代码?

Naw*_*waz 6

该表达式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
{

}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.