错误:'std :: ios_base :: ios_base(const std :: ios_base&)'是私有的 [英] error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private

查看:693
本文介绍了错误:'std :: ios_base :: ios_base(const std :: ios_base&)'是私有的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

通过这个类,我试图创建一个登录到文件的Logger类。但它给出错误像

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

我googled它,发现它是因为复制流。根据我的理解,在这段代码没有复制的流发生。

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.

推荐答案

static Logger getLogger()
{
   return log;
}

尝试返回记录器 by value,这需要一个复制构造函数。编译器生成的复制构造函数试图创建成员 debug 的副本。

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.

你可以实现一个复制构造函数(可能没有意义,因为 debug 成员将不同)或通过引用返回:

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

这是安全的,因为 log 静态存储持续时间

正确的调用如下所示:

Logger& l = Logger::getLogger();

在这种情况下 l Logger :: log

这篇关于错误:'std :: ios_base :: ios_base(const std :: ios_base&amp;)'是私有的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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