首页 文章

如何将fstream对象用作成员变量?

提问于
浏览
-2

以前,我会将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 '转换为'std :: ofstream * {aka std :: basic_ofstream *}'[-fpermissive]

2 回答

  • 4

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

    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) {}
    };
    
  • 5

    你可能想要

    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
    

相关问题