在构造函数类中初始化流,只使用c ++ 11 [英] Initialize ofstream in constructor class, only working with c++11

查看:252
本文介绍了在构造函数类中初始化流,只使用c ++ 11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使用

g++ -I. -std=c++0x -Wall -g -Werror *.cpp -o main

-std = c ++ 0x开关,它表示

but without the -std=c++0x switch, it says

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开关的情况下编译它?

How could I make it compile without the c++0x switch ?

代码:

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;
};


推荐答案

a std :: string 。您需要 char const * 构造函数: m_file(outputFilename.c_str())

prior to C++11 ofstream has no constructor accepting a std::string. You need the char const* constructor: m_file (outputFilename.c_str())

这篇关于在构造函数类中初始化流,只使用c ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆