4

我对这段代码有疑问:

#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;
}

有人可以解释我出了什么问题以及如何解决吗?谢谢。

4

3 回答 3

9

两个错误:

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

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

于 2010-10-02T21:37:51.793 回答
4

ifstream没有复制构造函数。A(std::ifstream input)意思是“用于A取值的ifstream 构造函数”。这要求编译器制作流的副本以传递给构造函数,因为不存在这样的操作,所以它不能这样做。

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


风格说明:while循环体A(input);, 构造了一个 type 的结构,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;
}
于 2010-10-02T21:37:22.283 回答
2

流是不可复制的。

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

struct A
{   
    A(std::ifstream& input)
                 ^^^^^
    {
        //some actions
    }
};
于 2010-10-02T21:38:07.800 回答