ここで回答済みの同様の質問をいくつか読みましたが、まだ理解していないので、重複として閉じる前にそのことを覚えておいてください:)。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>}’
Log.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;
}