error: ‘std::ios_base::ios_base(const std::ios_bas

2019-02-14 08:46发布

#include <iostream>
#include <fcntl.h>
#include <fstream>

using namespace std;

 class Logger
 {
    private:
            ofstream debug;
            Logger()
            {
                    debug.open("debug.txt");
            }
            static Logger log;
    public:
            static Logger getLogger()
            {
                    return log;
            }

            void  writeToFile(const char *data)
            {
                    debug << data;
            } 

            void close()
            {
                    debug.close();
            }               
};

Logger Logger::log;

Through this class i m trying to create a Logger class which logs into a file. But it gives error like

error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private

i googled it and found that its because of copying ofstreams. As far as i understand in this code no copying of ofstreams is taking place.

Can u guys help me out. Thanks in advance.

~

标签: c++ stream
1条回答
闹够了就滚
2楼-- · 2019-02-14 09:31
static Logger getLogger()
{
   return log;
}

attempts to return a Logger by value, which requires a copy-constructor. The compiler-generated copy-constructor attempts to make a copy of the member debug. Which is why you get the error.

You can either implement a copy constructor (probably doesn't make sense, since the debug member would be different) or return by reference:

static Logger& getLogger()
{
   return log;
}

which is safe in this case, since log has static storage duration.

A correct call would look like:

Logger& l = Logger::getLogger();

in which case l refers to Logger::log.

查看更多
登录 后发表回答