【问题标题】:Pointer to an fstream issue with >> operator?指向 >> 运算符的 fstream 问题?
【发布时间】:2015-07-20 14:20:51
【问题描述】:

我正在尝试使用文件流来读取输入,当我在类之间传输文件时,我需要能够维护指向文件的指针。以下是我正在尝试做的粗略概述:

class A {
friend class B;
public:
    void somefunction();

private:
    fstream o;
    B b;
};

class B {
   fstream * in;

   public:
        void input();
        void modify(fstream *);
};

这是我正在尝试使用的两个类的简单表示。我有一个像这样修改 fstream 的函数:

void A::somefunction() {
    B.modify(o);
}

void B::modify(fstream * o) {
     this -> in = o;
}

在这里,我传递了另一个 fstream,以便类 B 现在维护指向该文件的指针。但是,当我尝试使用它读取输入时,我失败了:

void B::input() {
    while (*in >> object) {
        cout << object << endl;
    }
}

该语句仅计算为 false 并且 while 循环不执行。我想知道这是否是流的问题,但我不确定。有人有什么建议吗?

编辑:

B b;
b.modify(o);

我想将 A 类中的 fstream o 传递给 B 类。我将 A 类中的 fstream * in 设置为 B 类中的 fstream o。我忘了添加 fstream o 正在从文件中读取,我想基本上将流“传输”到 B 类,以便它可以从文件中读取。

【问题讨论】:

  • 你能把所有的东西都打包成一些最小的可编译的例子然后贴在这里吗?特别是,您如何/在哪里将A 的流传递给B
  • @vsoftco 通过修改函数 - 我从 A 类传入 fstream o,然后在 B 类中将 fstream 设置为等于 o。这将维护指向 B 类中打开文件的指针, A 现在可以从中读取/写入。
  • 不明白。 oA 的成员,因此您需要A 的实例才能将成员o 传递给B 的实例。 A 需要有某种fstream* get_stream() const 成员函数,然后您可以在调用b.modify(a.get_stream()) 时调用它。

标签: c++ pointers fstream cin istream


【解决方案1】:

首先,streams are not copyable(它们的复制构造函数在 pre-C++11 中是私有的,在 C++11 和 C++14 中被删除)。如果您有 fstream 类型的成员,则需要将 std::move 加入其中(使用 C++11 或更高版本)。如果您不想使用(不能使用)C++11,那么您需要传递指针(或引用)。这是使用指针的一种方法:

#include <iostream>
#include <fstream>

class A
{
    std::fstream* o; // pointer to fstream, not fstream
public:
    A(std::fstream* o): o(o) {}
    std::fstream* get_fstream() const
    {
        return o;
    }
};

class B
{
    std::fstream* in;
public:
    void modify(std::fstream* o)
    {
        this -> in = o;
    }
    void input()
    {
        std::string object;
        while (*in >> object) {
            std::cout << object << std::endl;
        }
    }
};

int main()
{
    std::fstream* ifile = new std::fstream("test.txt");
    A a(ifile);
    B b;
    b.modify(a.get_fstream());
    b.input();
    delete ifile;
}

我更喜欢指针而不是引用,因为引用必须初始化并且以后不能更改。

【讨论】:

  • 我将尝试快速实现类似的东西 - 谢谢。我会告诉你进展如何。
  • @StormyGraveyard 很高兴它有帮助。
猜你喜欢
  • 2011-05-09
  • 1970-01-01
  • 2016-12-04
  • 2020-12-24
  • 2017-07-18
  • 2021-10-27
  • 2011-10-12
  • 2021-09-08
相关资源
最近更新 更多