我在这里阅读了几个类似的问题并得到了回答,但我还没有理解,所以在关闭之前请记住这一点:)。我想要一个带有 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
和一个文件流,因为 ofstream
是 ostream
的子类.
此外,在用户提供文件名的情况下,您仍然需要一些内容供引用引用,您不能直接使用它。我建议您存储实际的 ofstream
对象,(或 unique_ptr<ofstream>
),并制作 output_stream
引用它。确保声明 ofstream
在 ostream
之前 对象在你的类定义中引用,否则当你试图绑定(bind)初始化列表中的引用时,你将有未定义的行为。或者您可以将其设为指针而不是引用,然后在构造函数的主体中对其进行赋值。
关于c++ - 简单的 C++ 日志记录类 - ostream 引用初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18552489/