C++ 为什么这个编译器错误?- 没有匹配的函数调用'std::basic_ofstream<char>::open(std::string&)'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28521561/
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
why this compiler error? - no matching function for call to 'std::basic_ofstream<char>::open(std::string&)'
提问by beauxq
This works on Visual Studio and it works on GCC 4.9.2 on one computer.
这适用于 Visual Studio,适用于一台计算机上的 GCC 4.9.2。
But on a different computer, I think it's the same GCC 4.9.2 compiler, but it gives me this error.
但是在另一台计算机上,我认为它是相同的 GCC 4.9.2 编译器,但它给了我这个错误。
Am I missing something? What's going on?
我错过了什么吗?这是怎么回事?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string filename;
filename = "teststring";
ofstream fout;
fout.open(filename);
fout << "Hello world!" << endl;
fout.close();
return 0;
}
.
.
||=== Build: Debug in fileiotest (compiler: TDM32 GNU GCC Compiler 4.9.2 dw2) ===|
F:\Users\XXX\cpp\fileiotest\main.cpp||In function 'int main()':|
F:\Users\XXX\cpp\fileiotest\main.cpp|12|error: no matching function for call to 'std::basic_ofstream<char>::open(std::string&)'|
F:\Users\XXX\cpp\fileiotest\main.cpp|12|note: candidate is:|
F:\TDM-GCC-32\lib\gcc\mingw32.9.2-dw2\include\c++\fstream|716|note: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]|
F:\TDM-GCC-32\lib\gcc\mingw32.9.2-dw2\include\c++\fstream|716|note: no known conversion for argument 1 from 'std::string {aka std::basic_string<char>}' to 'const char*'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
回答by Lightness Races in Orbit
This overload's new in C++11, which means you need to pass -std=c++11
in the build command.
此重载是 C++11 中的新内容,这意味着您需要传入-std=c++11
build 命令。
In C++03, we used to write this:
在 C++03 中,我们曾经这样写:
fout.open(filename.c_str());