简体   繁体   English

将istream参数传递给类构造函数时出现问题

[英]problem passing in istream argument to a class constructor

I have the following code in my header file: 我的头文件中有以下代码:

class Factovisors {

    public:
        Factovisors(std::istream& strm):strm_(strm)
        {

        }
        void run()
        {
            unsigned int n,m;
            while (!strm_.eof()) {
            strm_ >> n >> m;

            if (isFact(n,m))
                std::cout << m << " divides " << n << "!\n";
            }
        }

        std::istream strm_;

};

My .cpp file has the following code. 我的.cpp文件具有以下代码。

 std::ifstream strm("factovisor.test");

    Factovisors   facto(strm);

    facto.run();

    strm.close();

The error my compiler gives me is: 我的编译器给我的错误是:

std::ios::basic_ios(const std::ios &) is not accessible from
std::istream::basic_istream(const std::istream &)

I imagine I am missing something really obvious. 我想我确实缺少一些明显的东西。 So any help would be greatly appreciated. 因此,任何帮助将不胜感激。

The problem is that istream is an "interface". 问题在于istream是一个“接口”。 It has pure virtual functions, so it doesn't make sense to have a copy of it. 它具有纯虚函数,因此没有副本是没有意义的。 What you might do is to keep a reference to the passed stream: 您可能要做的是保留对传递的流的引用:

std::istream& strm_;

strm_ could be ifstream or istringstream or any input stream derived from istream . strm_可以是ifstreamistringstream或从istream派生的任何输入流。

You can't copy-construct a stream because the base-class ios has its copy ctor private. 您无法复制构造流,因为基类ios的复制ctor私有。 Try making the stream member a reference, rather than a standalone object. 尝试使流成员成为引用,而不是独立对象。

You are trying to store a copy of the stream. 您正在尝试存储流的副本。 This will not work, since streams are not copyable. 这是行不通的,因为流不可复制。 Best you can do is store a reference or a pointer. 最好的办法是存储引用或指针。

However, if only one method is going to use the stream, just pass a reference to this method. 但是,如果只有一种方法要使用该流,则只需传递对该方法的引用即可。

Other problems: 其他问题:

        while (!strm_.eof()) {
        strm_ >> n >> m;

        if (isFact(n,m))

Eof is set when an attempt to read data fails because of this. 因此,当尝试读取数据失败时将设置Eof。 As it is you are bound to read the last entry twice. 因为它是您必读两次的最后一项。 Instead: 代替:

while (strm >> n >> m )
    if (isFact(n, m)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM