【问题标题】:How can I use an fstream object as a member variable?如何使用 fstream 对象作为成员变量?
【发布时间】:2016-09-02 20:43:16
【问题描述】:

以前,我会将 fstream 对象的地址传递给任何执行 I/O 操作的函数,包括构造函数。但我想尝试使 fstream 对象可用作成员变量,以便所有后续 I/O 操作都可以使用这些变量,而不是将它们作为参数传递。

考虑以下 Java 程序:

public class A {
    Scanner sc;

    public A(Scanner read) {
        sc = read;
    }
}

C++ 的等价物是什么?我试过这样做

class A {
    ofstream *out;

    public:
        A (ofstream &output) {
            out = output;
        }
};

但这给了我一个编译错误:

[错误] 从 'std::ofstream {aka std::basic_ofstream}' 到 'std::ofstream* {aka std::basic_ofstream*}' 的用户定义转换无效 [-fpermissive]

【问题讨论】:

  • 您不能将引用分配给指针。这些是不同的东西。
  • “但这给了我一个编译错误。”具体说明编译错误。请发minimal reproducible example
  • 另外,您要求的是输出,而不是像 scanner 所暗示的输入。
  • 你是对的,但我要求的是一般 I/O 操作。我使用哪一个对我来说并不重要。至于编译错误,我将编辑我的原始帖子以包含它。

标签: c++ io fstream


【解决方案1】:

我建议使用引用类型作为类的成员变量。

class A {
    ofstream& out;

    public:
        A (ofstream &output) : out(output) {}
};

比使用指针更简洁。

如果您希望 A 类型的对象从流中读取数据(如名称 Scanner 所暗示的那样),请使用 std::istream

class A {
    std::istream& in;

    public:
        A (std::istream &input) : in(input) {}
};

【讨论】:

  • 我刚刚注意到 OP 叫出了完全错误的树。他们想要输入,而不是输出。
  • @πάνταῥεῖ,好电话。幸运的是,同样的原则也适用于istream
  • 您好,谢谢您的回答!您能否解释一下为什么“A (ofstream &output) : out(output) {}” 有效但 A (ofstream &output) { out = output;没有?当我尝试后者时,它给了我一个“未初始化的引用成员'A::out'[-fpermissive]”错误。为什么前者不会导致同样的错误?
  • 必须使用成员初始化列表来初始化引用。它类似于在函数中初始化引用变量。你不能使用int i; int& ref; ref = i;。你必须使用int i; int& ref = i;
【解决方案2】:

你可能想要

class A {
    ofstream *out;

    public:
        A (ofstream &output) : out(&output) {
                                // ^ Take the address
        }
};

由于std::ofstream 专门用于文件,因此更好的接口是:

class A {
    ostream *out;

    public:
        A (ostream &output) : out(&output) {
        }
};

因此,您也可以将您的类透明地用于非面向文件的输出目标,例如

A a(std::cout); // writes to standard output rather than using a file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    相关资源
    最近更新 更多