为什么这个编译器错误? - 没有用于调用 'std::basic_ofstream<char>::open(std::string&)' 的匹配函数

why this compiler error? - no matching function for call to 'std::basic_ofstream<char>::open(std::string&)'

这适用于 Visual Studio 并且它适用于一台计算机上的 GCC 4.9.2。

但在不同的计算机上,我认为它是相同的 GCC 4.9.2 编译器,但它给我这个错误。

我错过了什么吗?怎么回事?

#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)) ===|

此重载在 C++11 中是新的,这意味着您需要在构建命令中传递 -std=c++11

在C++03中,我们曾经这样写:

fout.open(filename.c_str());