为什么会出现这个编译器错误?- 调用'std::basic_ofstream<char>::open(std::string&)'没有匹配功能

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

本文关键字:std gt lt char open 功能 string ofstream 为什么 编译器 错误      更新时间:2023-10-16

这适用于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:UsersXXXcppfileiotestmain.cpp||In function 'int main()':|
F:UsersXXXcppfileiotestmain.cpp|12|error: no matching function for call to 'std::basic_ofstream<char>::open(std::string&)'|
F:UsersXXXcppfileiotestmain.cpp|12|note: candidate is:|
F:TDM-GCC-32libgccmingw324.9.2-dw2includec++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-32libgccmingw324.9.2-dw2includec++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());