我不想在 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))
创建一个不能绑定(bind)到非常量引用的临时对象。
你为什么不这样做呢(同时阅读评论):
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
{
}
希望对您有所帮助。
关于c++ - 在类中初始化 ofstream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9450878/