gpt4 book ai didi

c++ - 在类中初始化 ofstream

转载 作者:行者123 更新时间:2023-11-30 00:56:49 24 4
gpt4 key购买 nike

我不想在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com