提问者:小点点

在C++中调用一个没有直接引用的函数是可能的吗?


这里是初学者

我正在尝试为我的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++程序员可能已经在翻白眼了,但你能不能好心告诉我,我将如何使它工作。

顺便说一句,我希望我做的对,这是我的第一个问题,所以我很抱歉如果它是坏的


共2个答案

匿名用户

规范的方法是使用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...");
}

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|调用|引用|函数)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?