开发者

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)
        {

开发者_JAVA技巧        }
        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.

 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". 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.


You can't copy-construct a stream because the base-class ios has its copy ctor private. 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. As it is you are bound to read the last entry twice. Instead:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜