构造函数问题中的C ++ std :: ifstream

时间:2010-10-02 21:33:11

标签: c++ constructor g++ ifstream

我对此代码有疑问:

#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 ++输出这个:

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

将其更改为此后编译(但这不能解决问题):

#include <fstream>

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

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

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

    return 0;
}

有人可以解释我的错误以及如何解决这个问题吗?感谢。

3 个答案:

答案 0 :(得分:8)

两个错误:

  • ifstream不可复制(将构造函数参数更改为引用)。
  • A(input);相当于A input;。因此编译器尝试调用默认构造函数。在它周围包裹parens (A(input));。或者只是给它命名A a(input);

另外,使用函数有什么问题?似乎只使用了类的构造函数,您似乎滥用它作为返回void的函数。

答案 1 :(得分:4)

ifstream没有复制构造函数。 A(std::ifstream input)表示“A的构造函数按值获取ifstream 。”这需要编译器制作流的副本以传递给构造函数,但由于不存在此类操作,因此无法执行此操作。

您需要通过引用传递流(意思是“使用相同的流对象,而不是它的副本。”)因此,将构造函数签名更改为A(std::ifstream& input)。请注意&符号,表示“引用”,对于函数参数,表示“通过引用传递此参数 而不是按值传递


文体说明while循环的正文A(input);构造了A类型的结构,然后在while时几乎立即销毁{1}}循环循环。你确定这是你想做的吗?如果这段代码已经完成,那么将它作为一个函数或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;
}

答案 2 :(得分:2)

Streams是不可复制的。

所以你需要通过引用传递。

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