C++ 在C+;中是否可以在没有直接引用的情况下调用函数+;?
这里是初学者 我想为我的C++学习项目做一个记录器,我已经设置了代码来管理日志记录本身,但是我不能让函数从其他类中工作。 这是我的“调试器”类 <>这不起作用,而你有经验的C++程序员可能已经滚动你的眼睛了,但是你能告诉我如何让它工作吗?C++ 在C+;中是否可以在没有直接引用的情况下调用函数+;?,c++,visual-studio,C++,Visual Studio,这里是初学者 我想为我的C++学习项目做一个记录器,我已经设置了代码来管理日志记录本身,但是我不能让函数从其他类中工作。 这是我的“调试器”类 这不起作用,而你有经验的C++程序员可能已经滚动你的眼睛了,但是你能告诉我如何让它工作吗? 顺便说一句,我希望我做得对,这是我的第一个问题,所以如果它不好,我很抱歉。您需要使用静态函数。这里有一些代码让你开始 class MSEdebug { public: MSEdebug(){} ~MSEdebug() {
顺便说一句,我希望我做得对,这是我的第一个问题,所以如果它不好,我很抱歉。您需要使用静态函数。这里有一些代码让你开始
class MSEdebug
{
public:
MSEdebug(){}
~MSEdebug() { logOutput.close(); }
static void debuglog(std::string info)
{
#ifdef DEBUG
std::cout << "LOG:" << info << std::endl;
#endif // DEBUG
if( ! logOutput.is_open() )
{
//first use - open logfile
logOutput.open("log.txt");
}
logOutput << "LOG:" << info << "\n";
}
static std::ofstream logOutput;
};
顺便说一句,有人建议“您需要一个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;
};
这可能是一种情况,在这种情况下,单例可能是有序的:
class调试{
私人:
MSEdebug(){logOutput.open(“log.txt”);}
~MSEdebug(){logOutput.close();}
公众:
静态调试&实例(){
静态调试;
返回调试;
}
void调试日志(std::string info){
#ifdef调试
std::cout看起来需要使用静态函数。debuglog
是MSEdebug
类的一个方法,所以需要一个类型为MSEdebug
的实际变量来调用它。类的成员函数默认为私有函数。您应该将debuglog
设为公共。@NateEldredge非常感谢您的帮助帽子回答。我想我可能“装模作样”我的问题,这正是我的意思,我不想在我想要使用它的每个类中创建MSEdebug类型的变量,所以我想知道是否可以不使用该变量。我将更改问题以更好地适应我实际提出的问题。您可以将其设置为内联并在类定义中初始化if。假设使用c++17。像这样的构造函数和析构函数对静态成员来说是危险的。我建议您删除它们。@Yksisarvinen True。但是这段代码应该是一个可行的第一个版本。@FrançoisAndrieux正确。我在回答中修复了这段代码。MSEdebug
类的c'tor和d'tor背后的想法是什么做简单事情的复杂且迂回的方式。对于具有多个方法的复杂类非常有用。new MSEdebug()的使用一个静态实例是足够的,当C++运行时停止时,也会被清理干净。非常感谢,我不希望这么多人这么快回复,你们大家都知道的模式有一个很好的属性:它们是文档化的并且已经被测试过了。在C++中的单模式模式。它们几乎总是工作,但是在一些角落的情况下可能失败。每当我可以,我坚持最佳实践和众所周知的模式,以便以后不会被一个角落的情况所捕获。作为一个老恐龙,我已经尝试了很多陷阱,现在努力远离它们…我试图说在那里。目前无法调用您的任务。
class MSEdebug
{
public:
MSEdebug(){}
~MSEdebug() { logOutput.close(); }
static void debuglog(std::string info)
{
#ifdef DEBUG
std::cout << "LOG:" << info << std::endl;
#endif // DEBUG
if( ! logOutput.is_open() )
{
//first use - open logfile
logOutput.open("log.txt");
}
logOutput << "LOG:" << info << "\n";
}
static std::ofstream logOutput;
};
std::ofstream MSEdebug::logOutput;
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...");