在构造函数类中初始化 ofstream,仅适用于 c++11
Initialize ofstream in constructor class, only working with c++11
以下代码使用
g++ -I. -std=c++0x -Wall -g -Werror *.cpp -o main
但是如果没有 -std=c++0x 开关,它说
main.cpp: In constructor ‘Out<T>::Out(const string&) [with T = double, std::string = std::basic_string<char>]’:
main.cpp:274:42: instantiated from here
main.cpp:34:113: erreur: no matching function for call to ‘std::basic_ofstream<char>::basic_ofstream(const string&, std::_Ios_Openmode)’
main.cpp:34:113: note: candidates are:
/usr/include/c++/4.6/fstream:629:7: note: std::basic_ofstream<_CharT, _Traits>::basic_ofstream(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits<char>, std::ios_base::openmode = std::_Ios_Openmode]
/usr/include/c++/4.6/fstream:629:7: note: no known conversion for argument 1 from ‘const string {aka const std::basic_string<char>}’ to ‘const char*’
/usr/include/c++/4.6/fstream:614:7: note: std::basic_ofstream<_CharT, _Traits>::basic_ofstream() [with _CharT = char, _Traits = std::char_traits<char>]
/usr/include/c++/4.6/fstream:614:7: note: candidate expects 0 arguments, 2 provided
/usr/include/c++/4.6/fstream:588:11: note: std::basic_ofstream<char>::basic_ofstream(const std::basic_ofstream<char>&)
/usr/include/c++/4.6/fstream:588:11: note: candidate expects 1 argument, 2 provided
如何在没有 c++0x 开关的情况下使其编译?
法典:
template <typename T>
class Out
{
public:
Out(const std::string& outputFilename) : m_file(outputFilename, std::ios_base::out | std::ios_base::app) {}
void write(const std::string &text)
{ m_file << text << "n"; }
void flush() { m_file << std::flush; }
void fake(T t) { std::cout << t << std::endl; }
private:
std::ofstream m_file;
};
在 C++11 之前,ofstream 没有接受std::string
的构造函数。您需要构造函数char const*
:m_file (outputFilename.c_str())
在 C++11 中,构造函数: 添加了explicit ofstream (const string& filename, ios_base::openmode mode = ios_base::out);
,而以前的版本没有。
您需要使用构造函数explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);
例:
Out(const std::string& outputFilename) : m_file(outputFilename.c_str(), std::ios_base::out | std::ios_base::app) {}
相关文章:
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 适用于 WebView2 旧版本的示例应用程序
- 在 NVIDIA GEFORCE GTX 1050 上下载适用于 Windows 10 的 openCL 1.2
- __attribute__(优化(0))) 是否适用于"recursively"?
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- 使用一个参数的模板函数时出错(适用于 2)
- 使用 适用于 Android 和 iOS 的 tf-lite C++ API
- 为什么这适用于 G++ 而不是 CLANG?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 适用于 C++11 的线程,使用 new 创建
- 适用于 C++11 的 Clang++ 3.3 中的线程支持
- 哪些适用于 Windows 的 C++11 编译器支持新的类型特征,如"is_nothrow_move_constructible"?
- 将 C++11 正则表达式与 gcc 4.8.2 一起使用时会出现奇怪的结果(但适用于 Boost 正则表达式)
- C++11 正则表达式是否适用于 UTF-8 字符串
- 在构造函数类中初始化 ofstream,仅适用于 c++11
- c ++ 11 参数包在 Apple LLVM 7.0.0 中存在错误行为,但适用于 GCC-5.1
- 警告:扩展初始化器列表仅适用于STD c++ 11
- C++11 cmath 函数不在 std 命名空间中,适用于 android NDK w/gcc-4.8 或 clang