【发布时间】:2013-01-24 18:05:16
【问题描述】:
我正在尝试为我在学校的项目创建一个 Log 类。它需要能够根据传递的参数将信息写入标准输出或文件。我正在研究如何做到这一点,我偶然发现了一个有类似问题的线程:Obtain a std::ostream either from std::cout or std::ofstream(file)
这个线程和我自己的唯一区别是我想在一个班级里做。虽然他们使用std::ostream out(buf) 并使用 buf 即时构建 ostream,但正在查看解决方案。如何在我的 Log 类中正确声明它,以便只有在我进入我的 Log 构造函数后才能构造“out”对象?
我在下面快速尝试了一下,但我不确定它是否正确或我是否走在正确的轨道上。感谢任何帮助,谢谢。
编辑:在我让这个 Log 类正常工作后,我希望能够做到 out << "Some string" << endl;。
EDIT2:我现在收到一个错误,下面的新代码error : 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char, _Traits = std::char_traits<char>]' is protected
// log.h
#include <string>
#include <fstream>
#ifndef LOG_H_
#define LOG_H_
class Log
{
public:
enum Mode { STDOUT, FILE };
// Needed by default
Log(const char *file = NULL);
~Log();
// Writing methods
void write(char *);
void write(std::string);
private:
Mode mode;
std::streambuf *buf;
std::ofstream of;
std::ostream out;
};
#endif
// log.cpp
#include "log.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
Log::Log(const char *file)
{
if (file != NULL)
{
of.open(file);
buf = of.rdbuf();
mode = FILE;
}
else
{
buf = std::cout.rdbuf();
mode = STDOUT;
}
// Attach to out
out.rdbuf(buf);
}
Log::~Log()
{
if (mode == FILE)
of.close();
}
void Log::write(std::string s)
{
out << s << std::endl;
}
void Log::write(char *s)
{
out << s << std::endl;
}
【问题讨论】:
-
我会添加
char *file = NULL或类似的东西,这样您就不必将Log的任何参数传递给标准输出。 - 在头文件中给出你的默认参数,而不是实现[你在任何调用 Log() 的代码中都需要它们,这可能不是你的“log.cpp”或任何它可能被调用的东西。 -
好建议!添加了。哦,好吧,我不记得默认参数放在标题中,而不是实现。谢谢,我已经有一段时间没有做任何认真的 C++ 编程了
-
除此之外,代码看起来正确 当你尝试它时会发生什么? [顺便想一下,你真的需要一个“模式”和一个“char *file” - 为什么不使用“char *file”来指示输出应该是文件还是标准输出 - 那样,你不需要'不必有两个参数]。
-
另一个很棒的建议,该死的我需要离开“生锈”区哈哈
标签: c++