C++ 没有匹配的函数 - ifstream open()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16552753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
No matching function - ifstream open()
提问by user2252786
This is the part of the code with an error:
这是有错误的代码部分:
std::vector<int> loadNumbersFromFile(std::string name)
{
std::vector<int> numbers;
std::ifstream file;
file.open(name); // the error is here
if(!file) {
std::cout << "\nError\n\n";
exit(EXIT_FAILURE);
}
int current;
while(file >> current) {
numbers.push_back(current);
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return numbers;
}
And well, I kind of have no idea what is going on. The whole thing compiles properly in VS. However I need to compile this with dev cpp.
好吧,我有点不知道发生了什么。整个事情在 VS 中正确编译。但是我需要用 dev cpp 编译它。
I commented out the line throwing errors in the code above. The errors are:
我注释掉了上面代码中抛出错误的行。错误是:
no matching function for call 'std::basic_ifstream<char>::open(std::string&)
no matching function for call 'std::basic_ofstream<char>::open(std::string&)
In different parts of code I get errors like numeric_limits is not a member of std
, or max() has not been declared
, although they exist in iostream
class and everything works in VS.
在代码的不同部分,我得到了诸如numeric_limits is not a member of std
, 或 之类的错误max() has not been declared
,尽管它们存在于iostream
类中并且一切都在 VS 中工作。
Why am I getting this error?
为什么我收到这个错误?
回答by hmjd
Change to:
改成:
file.open(name.c_str());
or just use the constructor as there is no reason to separate construction and open:
或者只是使用构造函数,因为没有理由将构造和打开分开:
std::ifstream file(name.c_str());
Support for std::string
argumentwas added in c++11.
在 c++11 中添加了对std::string
参数的支持。
As loadNumbersFromFile()
does not modify its argument pass by std::string const&
to document that fact and avoid unnecessary copy.
AsloadNumbersFromFile()
不修改其参数传递std::string const&
以记录该事实并避免不必要的复制。