C ++ std :: ifstream in constructor

I have a problem with this code:

#include <fstream>

struct A
{   
    A(std::ifstream input)
    {
        //some actions
    }
};

int main()
{
    std::ifstream input("somefile.xxx");

    while (input.good())
    {
        A(input);
    }

    return 0;
}

g ++ gives me this:

$ g++ file.cpp
file.cpp: In function `int main()':
file.cpp:17: error: no matching function for call to `A::A()'
file.cpp:4: note: candidates are: A::A(const A&)
file.cpp:6: note:                 A::A(std::ifstream)

After changing it to compilation (but this does not solve the problem):

#include <fstream>

struct A
{   
    A(int a)
    {
        //some actions
    }
};

int main()
{
    std::ifstream input("dane.dat");

    while (input.good())
    {
        A(5);
    }

    return 0;
}

Can someone explain to me what happened and how to fix it? Thank.

+3
source share
3 answers

Two errors:

  • ifstream not copied (change the constructor parameter to a link).
  • A(input);equivalent to A input;. Thus, the compiler tries to call the default constructor. Wrap the pair around him (A(input));. Or just provide a name A a(input);.

Also, what's wrong with using a function for this? Only the constructor of the class is used, which seems to be used as a function that returns void.

+8

ifstream . A(std::ifstream input) " A, ifstream ". , , .

( " , ".) A(std::ifstream& input). , "" , , " , ".


: while, A(input);, A, while. , , ? , - A, :

static void process(std::istream& stream)
{
    // some actions
    // note stream is declared as std::istream&; this lets you pass
    // streams that are *not* file-based, if you need to
}

int main()
{
    std::ifstream input("somefile.xxx");

    while (input.good())
    {
        process(input);
    }

    return 0;
}

struct A
{   
    A()
    {
        // default constructor for struct A
    }

    void process(std::istream& stream)
    {
        // some actions
    }
};

int main()
{
    std::ifstream input("somefile.xxx");

    A something;
    while (input.good())
    {
        something.process(input);
    }

    return 0;
}
+4

Streams are not copied.

So, you need to follow the link.

struct A
{   
    A(std::ifstream& input)
                 ^^^^^
    {
        //some actions
    }
};
+2
source

All Articles