[英]C++11 error no match for call to Ifstream outside main
我是c ++的新手,尝试自己学习。
我发现了几个与此相关的问题,但没有一个问题能真正回答。 我已经启用了c ++ 11,据我所知,ifstream应该接受一个std :: string。 我也曾在Visual Studio,CLion和Eclipse Neon中尝试过此方法,结果完全相同。
我还在运行时检查了__cplusplus的值,我知道它的设置为201103,这对于构造函数的重载是必需的。
本质上,如果我在使用std :: string的主函数中使用std :: ifstream我没有问题。 另一方面,如果我尝试将其传递给另一个类,该类在另一个文件中在Eclipse和Clion中收到此错误:
“错误:与'(std :: ifstream {aka std :: basic_ifstream})(std :: __ cxx11 :: string&)'infile(filename)的调用不匹配;”
而在Visual Studio中,此错误:“错误C2064:术语未求值为带有1个参数的函数”
两种错误都指向同一行,如下面的代码块所示。 我想知道自己在做错什么,因为我想在类中使用ifstream。
// main.cpp
#include test.h
int main() {
std::string name("test.txt");
TestClass test (name);
std::ifstream testfile(name);
return 0;
}
// test.h
#include <fstream>
class TestClass{
std::ifstream infile;
public:
TestClass(std::string filename); // have also tried with std::string& filename
}
// test.cpp
TestClass::TestClass(std::string filename){ // again have tried using string&
infile(filename); /** ERROR **/
}
std::ifstream
没有提供operator()(std::string)
重载。 因此
infile(filename);
在构造函数体内无法编译。
有一个构造函数带有const std::string&
但是可以在您的类成员初始化器列表中使用:
TestClass::TestClass(std::string filename) : infile(filename) {
// Omit that completely: infile(filename); /** ERROR **/
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.