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

标签 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;
}

有人可以向我解释哪里出了问题以及如何解决吗?谢谢。

最佳答案

两个错误:

  • ifstream 不可复制(将构造函数参数更改为引用)。
  • A(input); 等同于A input;。因此,编译器会尝试调用默认构造函数。将其包裹起来 (A(input));。或者只是给它起个名字 A a(input);

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

关于C++ std::ifstream 在构造函数中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3847611/

相关文章:

c++ - libopencv_core.so.2.4 : error adding symbols: DSO missing from command line

c++ - Glut:如何知道窗口何时移动?

c++ - 在旧版 Visual Studio 中开发的链接库

c++ - g++ 静态库的顺序很重要吗?

Scala:使用构造函数参数扩展具体类

c++ - 我可以显式调用类的构造函数和析构函数吗?

c++ - 如何在运行时摆脱 LD_LIBRARY_PATH?

c++ - C++中的类接口(interface)继承

c++ - Gstreamer - 示例 1 中的错误

java - 如何获得使用 java 创建的时钟的正确输出?