我能否返回一个 ofstream 对象以初始化另一个 ofstream 对象?

3

我想在一个函数中打开文件并将打开文件对象返回给主函数,然后在另一个函数中使用它来填充该文件。但是编译器提示我正在尝试访问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());

哪个更好?在主函数中声明对象并通过引用将其传递给两个函数?还是使用移动构造函数?

3
你返回了一个指向临时对象的引用。ofstream ost = x() 试图拷贝构造 ost(其中 x() 是左值)。 - David G
2个回答

3
在C++11中,各种流类都有移动构造函数,也就是说,您可以从函数中移动一个std::ofstream并从中初始化一个std::ofstream(尝试从std::ofstream初始化std::ostream不起作用)。也就是说,假设您使用-std=c++11编译,并且随版本的gcc一起发布的libstdc++已经更新以支持这些构造函数。请注意保留HTML标记。

0

您可以将一个 ofstream 对象的引用传递到函数中:

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");
}

然后,在main函数中:

int main()
{
    ofstream ost;
    open_outfile(ost);
    populate_outfile(ost, readings);
    keep_window_open();
}

3
如果OP没有更新的编译器,那么这是一个好答案,虽然现在有移动语义了,但这并不是必需的。 - Mooing Duck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接