这里是初学者
我正在尝试为我的C++学习项目制作一个“记录器”,我已经设置了代码来管理日志记录本身,但是我无法从其他类获得该功能。
这是我的“调试器”类
class MSEdebug
{
MSEdebug(){logOutput.open("log.txt");}
~MSEdebug() { logOutput.close(); }
void debuglog(std::string info)
{
#ifdef DEBUG
std::cout << "LOG:" << info << std::endl;
#endif // DEBUG
logOutput << "LOG:" << info << "\n";
}
std::ofstream logOutput;
};
我想做的是:
#include "MSE_debug.h"
//...
MSEapp::debugTest()
{
MSEdebug::debuglog("Test, 1, 2, 3...");
}
现在这是行不通的,你们有经验的C++程序员可能已经在翻白眼了,但你能不能好心告诉我,我将如何使它工作。
顺便说一句,我希望我做的对,这是我的第一个问题,所以我很抱歉如果它是坏的
规范的方法是使用singleton模式来拥有msedebug
类的唯一实例,该实例很容易访问。
class MSEdebug
{
MSEdebug(){logOutput.open("log.txt");}
public:
~MSEdebug() { logOutput.close(); }
void debuglog(std::string info)
{
#ifdef DEBUG
std::cout << "LOG:" << info << std::endl;
#endif // DEBUG
logOutput << "LOG:" << info << "\n";
}
static MSEdebug& getInstance() {
static MSEdebug instance;
return instance;
}
private:
std::ofstream logOutput;
};
然后您可以这样使用它:
MSEdebug::getInstance().debuglog("Test, 1, 2, 3...");
这可能是一个单例可能是有序的情况:
class MSEdebug {
private:
MSEdebug(){ logOutput.open("log.txt"); }
~MSEdebug() { logOutput.close(); }
public:
static MSEdebug& instance(){
static MSEdebug debug;
return debug;
}
void debuglog(std::string info) {
#ifdef DEBUG
std::cout << "LOG:" << info << '\n';
#endif // DEBUG
logOutput << "LOG:" << info << '\n';
}
private:
std::ofstream logOutput;
};
用法如下:
#include "MSE_debug.h"
//...
MSEapp::debugTest()
{
MSEdebug::instance().debuglog("Test, 1, 2, 3...");
}