代码之家  ›  专栏  ›  技术社区  ›  Manuel

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

  •  -2
  • Manuel  · 技术社区  · 8 年前

    以前,我会将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;
            }
    };
    

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

    [Error]用户定义的从“std::ofstream{aka std::basic_ofstream}”到“std::ofstreak*{aka std::basic_ ofstreag*}”的转换无效[-fpermissive]

    2 回复  |  直到 8 年前
        1
  •  6
  •   R Sahu    8 年前

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

    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) {}
    };
    
        2
  •  4
  •   πάντα ῥεῖ    8 年前

    你可能想要

    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