这段代码有问题:
#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/