为什么使用临时性std :: string或“常规”变量构造ofstream会有所不同

时间:2018-11-12 09:56:30

标签: gcc c++17

如果我这样写,为什么对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;

}

0 个答案:

没有答案