Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::ifstream in constructor problem

I've got 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++ outputs 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 this it compile (but that is not solving 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 me what's wrong and how to fix it? Thanks.

like image 578
darvan Avatar asked Dec 08 '22 01:12

darvan


1 Answers

Two bugs:

  • ifstream is not copyable (change the constructor parameter to a reference).
  • A(input); is equivalent to A input;. Thus the compiler tries to call the default constructor. Wrap parens around it (A(input));. Or just give it a name A a(input);.

Also, what's wrong with using a function for this? Only the class's constructor is used it seems, which you seem to abuse as a function returning void.

like image 155
Johannes Schaub - litb Avatar answered Dec 21 '22 23:12

Johannes Schaub - litb