在类中初始化流
问题描述:
我不想在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’
如何修复代码?
答
表达式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
{
}
希望有所帮助。
答
只有在特殊情况下,您将对另一个对象的引用用作类数据成员。通常你想在成员对象上使用类的生命期依赖。通常,你的班级在复制和分配方面受到限制。如果您确实需要参考,则该对象必须已创建。
来电:
ofstream ouf("someFileName.txt");
test testObj(ouf)
你的类的头:
test::test(ofstream& ous) : ofs(ous) { }
注意,如果*是*声明为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