dar*_*van 4 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;
}
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
将其更改为此后编译(但这不能解决问题):
#include <fstream>
struct A
{
A(int a)
{
//some actions
}
};
int main()
{
std::ifstream input("dane.dat");
while (input.good())
{
A(5);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释我有什么问题以及如何解决它?谢谢.
两个错误:
ifstream 不可复制(将构造函数参数更改为引用).A(input);相当于A input;.因此编译器尝试调用默认构造函数.包裹它周围的parens (A(input));.或者只是给它一个名字A a(input);.另外,使用函数有什么问题?似乎只使用了类的构造函数,您似乎滥用它作为函数返回void.