我想在一个函数中打开文件并将打开文件对象返回给主函数,然后在另一个函数中使用它来填充该文件。但是编译器提示我正在尝试访问iostream的私有成员。是否有方法可以实现这个操作?如何实现?
ofstream& open_outfile()
{
string outfile;
cout << "Please enter the name of the file:";
cin >> outfile;
ofstream ost(outfile.c_str());
if (!ost) error("can't open out file");
return ost;
}
//...............
int main()
{
//...some code
ofstream ost = open_outfile();//attempt 1
//ofstream ost() = open_outfile();//attempt 2
populate_outfile(ost, readings);
keep_window_open();
}
我在《C++编程语言》中发现了这个语法,它似乎可以工作:
ofstream ost = move(open_outfile());
哪个更好?在主函数中声明对象并通过引用将其传递给两个函数?还是使用移动构造函数?
ofstream ost = x()
试图拷贝构造ost
(其中x()
是左值)。 - David G