0

以下代码使用流畅地编译

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

2 回答 2

4

在 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) {}

于 2013-10-25T07:06:35.667 回答
4

在 C++11 之前 ofstream 没有构造函数接受std::string. 您需要char const*构造函数:m_file (outputFilename.c_str())

于 2013-10-25T07:05:15.450 回答