c++ - 简单的 C++ 日志记录类 - ostream 引用初始化

标签 c++ logging reference cout ostream

我在这里阅读了几个类似的问题并得到了回答,但我还没有理解,所以在关闭之前请记住这一点:)。我想要一个带有 Print() 方法的简单 Log 对象。如果 Log 构造时不带参数,则记录到 cout。否则,参数描述完成日志记录的文件。

(我怀疑部分问题在于理解所有 stream 类之间的关系。)

编译时报错:

Log.cpp:11:23: error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream<char>&}’ from expression of type ‘std::ostream {aka std::basic_ostream<char>}’

日志.h:

#ifndef LOG_H
#define LOG_H
#include <string>
#include <fstream>

class Log {

public:
    Log();
    Log(const char*, const char*);

    void Print(const char*  msg,...);

private:
    // instance contains a reference to ostream
    std::ofstream&  output_stream;
};

#endif

日志.cpp:

#include "Log.h"
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <fstream>

// Constructor w/no parms = log to cout
Log::Log() :
    output_stream(cout)
{}

// Constructor w/parms = log to file
Log::Log(const char* dir, const char* file) {
    string output_file_name = string(dir) + "/" + string(file);
    output_stream.open(output_file_name.c_str(), std::ofstream::out);
}

// Print() sends output to the stream (we'll do printf semantics later)
void
Log::Print(const char* msg,...) {
    output_stream << msg << endl;
}

最佳答案

cout不是 ofstream 类型, 所以你不能绑定(bind) ofstream引用它。 output_stream应该是类型 ostream&相反,这将允许它引用 cout和一个文件流,因为 ofstreamostream 的子类.

此外,在用户提供文件名的情况下,您仍然需要一些内容供引用引用,您不能直接使用它。我建议您存储实际的 ofstream对象,(或 unique_ptr<ofstream> ),并制作 output_stream引用它。确保声明 ofstreamostream 之前 对象在你的类定义中引用,否则当你试图绑定(bind)初始化列表中的引用时,你将有未定义的行为。或者您可以将其设为指针而不是引用,然后在构造函数的主体中对其进行赋值。

关于c++ - 简单的 C++ 日志记录类 - ostream 引用初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18552489/

相关文章:

python - 登录类(class) - Python

php - 为什么 PHP/Laravel 不增加这个值?

C++ : alternative for Vector of references to avoid copying large data

java - 设置 HashMap 线程安全吗?

c++ - 未按预期调用移动构造函数

java - 在有效日志级别检查的上下文中,Log4j2 中的替换参数和 Java lambda 表达式有什么区别?

c++ - 虚拟的弃用协变返回类型

java - 无法使用log4j生成日志文件

c++ - 使用 fscanf 设置不同类中的变量

c++ - Citeulike 科学文章搜索错误