C ++ std :: ifstream在构造函数中的问题 [英] C++ std::ifstream in constructor problem

查看:416
本文介绍了C ++ std :: 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++ 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)

将其更改为this之后,问题):

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.

推荐答案

两个错误:


  • ifstream 不可复制(将构造函数参数更改为引用)。

  • ; 等效于 A输入; 。因此,编译器尝试调用默认构造函数。在它周围封装(A(输入)); 。或者只是给它一个名字 A(输入);

  • 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);.

,使用一个函数为什么有什么问题?只有类的构造函数被使用,似乎,你似乎滥用作为一个函数返回 void

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.

这篇关于C ++ std :: ifstream在构造函数中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆