我实现了一个非常简单(错误)的记录器类.它看起来像这样:
#pragma once
#include <string>
extern const char* LOG_DEFAULT_TEXT = "<LOG>\n\n";
class Log
{
public:
Log() : _logs(0), _log(LOG_DEFAULT_TEXT) {};
void add(const char *str, bool nl=true);
void clear();
const char* get() const { return _log.c_str(); }
int getNumLogs() const { return _logs; }
private:
std::string _log;
int _logs;
};
Run Code Online (Sandbox Code Playgroud)
现在我的问题是,我说这个Main类,包含我的程序可能包含的所有其他对象,以及这个Log类.显然我希望我的Main类中的这些"其他对象"能够在Main中使用Log对象,因此简单的解决方案是将指针传递给每个类的构造函数,以便它可以使用Log对象.
我在谈论这样的事情:
//Main.h
...
#include "Log.h"
class Main() {
public:
...
private:
Log _log;
ImportantObject1(&_log); //pass a pointer to _log
ImportantObject2(&_log); //..same
};
Run Code Online (Sandbox Code Playgroud)
这个解决方案看起来太笨拙,所以我问是否有不同的方法可以实现我想要完成的任务,即错误记录.
这是单身人士有意义的罕见情况之一:
class Log
{
public:
void add(const char *str, bool nl=true);
void clear();
const char* get() const { return _log.c_str(); }
int getNumLogs() const { return _logs; }
static Log& instance() {
static Log theInstance;
return theInstance;
}
private:
Log() : _logs(0), _log(LOG_DEFAULT_TEXT) {};
std::string _log;
int _logs;
};
Run Code Online (Sandbox Code Playgroud)
这样您就可以在其他地方使用它来访问
Log::instance().add("Blah Blah",true);
Run Code Online (Sandbox Code Playgroud)