如果我这样写,为什么对ofstream
有所不同:
std::ofstream out(std::string(path));
或
std::string strPath = std::string(path);
std::ofstream out(strPath);
如果我只将它们都构造好,就可以编译(gcc 8.1.1)
但是,一旦我想使用std::string
向文件中写入<<
,就会出现以下错误:
与'operator <<'不匹配(操作数类型为'std :: basic_ofstream(std :: __ cxx11 :: string)'{aka'std :: basic_ofstream(std :: __ cxx11 :: basic_string)'}和' std :: __ cxx11 :: string'{aka'std :: __ cxx11 :: basic_string'})
所以这失败了:
#include <fstream>
#include <iostream>
#include <string>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
int main() {
std::string data = "some data";
fs::path path = "test.txt";
std::ofstream out(std::string(path));
out << data;
}
但这可行:
#include <fstream>
#include <iostream>
#include <string>
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
int main() {
std::string data = "some data";
fs::path path = "test.txt";
std::string strPath(path);
std::ofstream out(strPath);
out << data;
}