C++ 我可以返回ofstream的一个对象来初始化ofstream的另一个对象吗?
我想在一个函数中打开一个文件,将打开的文件对象返回到main,然后在另一个函数中使用它 函数来填充文件。编译器似乎告诉我,我正在尝试访问iostream的私有成员。有什么方法可以做到这一点吗?如何做到C++ 我可以返回ofstream的一个对象来初始化ofstream的另一个对象吗?,c++,c++11,struct,iostream,C++,C++11,Struct,Iostream,我想在一个函数中打开一个文件,将打开的文件对象返回到main,然后在另一个函数中使用它 函数来填充文件。编译器似乎告诉我,我正在尝试访问iostream的私有成员。有什么方法可以做到这一点吗?如何做到 ofstream& open_outfile() { string outfile; cout << "Please enter the name of the file:"; cin >> outfile; ofstream os
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();
}
哪个更好?在main中声明对象并通过引用ost传递给这两个函数?还是使用移动构造函数?您可以将对流的
对象的引用传递给函数:
void open_outfile(/*out*/ ofstream &ost)
{
string filename;
cout << "Please enter the name of the file:";
cin >> filename;
ost.open(filename.c_str());
if (!ost) error("can't open out file");
}
在C++11中,各种流类都有move构造函数,也就是说,您可以从函数中移动std::ofstream
,并从函数中初始化std::ofstream
(尝试从std::ofstream
初始化std::ofstream不起作用)也就是说,假设您使用-std=c++11
进行编译,并且随您的gcc
版本一起提供的libstdc++
版本已更新,以支持这些构造函数。您正在返回对临时的引用。ofstream ost=x()
正在尝试复制构造函数ost
(其中x()
是一个左值)。现在我们有了移动语义,这是不必要的,但是如果OP没有更新的编译器,这是一个很好的答案
void open_outfile(/*out*/ ofstream &ost)
{
string filename;
cout << "Please enter the name of the file:";
cin >> filename;
ost.open(filename.c_str());
if (!ost) error("can't open out file");
}
int main()
{
ofstream ost;
open_outfile(ost);
populate_outfile(ost, readings);
keep_window_open();
}