[英]Why does << operator not work on derived class from ofstream?
首先,我看到很多帖子說從ostream
派生一個類是非平凡的,但這也是可以理解的,因為“ostream”本身需要為流提供一個緩沖區。
從fstream
或ofstream
派生怎么樣? 我認為這應該很簡單,因為這些基類確實設置了緩沖區,並且從它們派生出的只是實例化fstream
並因此封裝了它。
現在我正在創建一個看起來像這樣的日志文件(頭文件)
class lfstream : public std::ofstream
{
public:
lfstream();
~lfstream();
void log(const std::string &text);
protected:
std::ofstream logfile;
char logfname[32];
};
extern lfstream ls;
對應的cpp文件是
lfstream ls; // global object of log file so I can write to it
lfstream::lfstream() : logfname("Mylog.txt")
{
logfile.open(logfname, std::ios_base::out | std::ios_base::app);
}
lfstream::~lfstream()
{
}
void lfstream::log(const std::string &text)
{
logfile << text;
}
現在在 main() 函數中
int main(int argc, char * argv)
{
// this is for camparison, << operator works on ofstream
std::ofstream stockstream("ostream_test.txt");
stockstream << "<< test ostream" << std::endl; // works
// But << doesn't work on my derived class which is also a stream
ls << "<< test ls stream"; // why this doesn't go into the file?
ls.log("This works"); // but this does
}
所以我的第一個問題是,是否像上面一樣從ostream
派生? 其次,為什么<<
在派生類上不起作用?
更新
所以我的實現是錯誤的。 我eleminated成員變量ofstream
對象現在的構造變成這樣:
lfstream::lfstream() : logfname("debug_log.txt"), std::ofstream(logfname )
{
}
但是我現在如何實現 log() 函數呢?
更新 2
我的日志實際上確實打印了更多數據並相應地對其進行了格式化。 這就是我不只實例化ofstream
的原因
void lfstream::log(const std::string &text)
{
const time_t ctt = time(0);
int threadID = GetCurrentThreadId();
logfile << std::setw(40) << std::left << text << " thread id = " << threadID << "\t" << asctime(localtime(&ctt)); // << std::endl;
}
這意味着我可以調用ls.log(...)
並進行格式化。
我正在發布答案。 我的原始代碼有缺陷,因為我同時使用了組合和繼承(感謝指出這一點的評論)。 這兩種方法都提供了不同形式的解決方案,因此首先要決定使用哪一種。
作品
我的班級正在聲明std::ofstream logfile;
所以我不必從ofstream
派生,只需將工作委托給它的成員變量。 這是組成。
遺產
由於我的類是從std::ofstream
派生的,因此我不必聲明相同的成員變量。 刪除后,該類現在看起來如下所示。 這個想法是模仿ofstream
,實現相同的構造函數並在其中實例化ofstream
類的基類(我只實現了一個構造函數)。
lfstream::lfstream(const std::string& logfilename) : _logfname(logfilename),
std::ofstream(logfilename)
{
}
lfstream::~lfstream()
{
}
void lfstream::log(const std::string &text)
{
*this << text;
}
這確實解決了原始問題,現在<<
適用於我的派生類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.