2012-10-18 37 views
4
#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類,它將登錄到一個文件中。但它給錯誤如錯誤:'std :: ios_base :: ios_base(const std :: ios_base&)'是私人的

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

我GOOGLE了它,發現它因爲複製的流。據我所知,在這段代碼中沒有複製ofstreams正在發生。

你們能幫我一個忙嗎? 在此先感謝。

回答

6
static Logger getLogger() 
{ 
    return log; 
} 

嘗試返回Logger的價值,這需要一個拷貝構造函數。編譯器生成的複製構造函數嘗試複製成員debug。這就是你得到錯誤的原因。

您可以實現一個拷貝構造函數(可能是沒有意義的,因爲debug成員將是不同的)或引用返回:

static Logger& getLogger() 
{ 
    return log; 
} 

這是在這種情況下,安全的,因爲log靜態存儲時間爲

正確的電話看起來像:

在這種情況下
Logger& l = Logger::getLogger(); 

lLogger::log

+0

感謝一噸:) – Chaitanya

+0

@Chaitanya隨時! –

相關問題