1

我有以下类,Base 和 Derived,当我编译编译器时抱怨它无法创建 DLog 的实例,因为它是抽象的。

有人能告诉我如何解决这个错误吗?

我猜这是因为并非两个纯虚函数都没有在派生中实现。

class Logger
{
public:

    virtual void log(int debugLevel, char* fmt, ...) = 0;
    virtual void log(string logText, int debugLevel, string threadName = "") = 0;

    static Logger* defaultLogger() {return m_defaultLogger;}
    static void setDefaultLogger(Logger& logger) {m_defaultLogger = &logger;}

protected:

    static Logger* m_defaultLogger;
};

class DLog : public Logger
{
public:
    DLog();
    ~DLog();

    static DLog *Instance();
    static void Destroy();

    void SetLogFilename(std::string filename);
    void SetOutputDebug(bool enable);
    std::string getKeyTypeName(long lKeyType);
    std::string getScopeTypeName(long lScopeType);
    std::string getMethodName(long lMethod);

    virtual void log(string logText, int debugLevel)
    {
        Log(const_cast<char*>(logText.c_str()));
    }

    void Log(char* fmt, ...);

private:

    static DLog *m_instance;

    std::string m_filename;
    bool m_bOutputDebug;
};

// DLog 实例化为单例

DLog *DLog::Instance()
{
    if (!m_instance)
        m_instance = new DLog();
    return m_instance;
}
4

2 回答 2

2
virtual void log(string logText, int debugLevel, string threadName = "") = 0;

尚未在 DLog 类中实现。您必须实现它,因为它在基类中是纯虚拟的。

您可能在第一次重载login 时就是这个意思DLog

virtual void log(string logText, int debugLevel, string /*threadname*/)
{
    Log(const_cast<char*>(logText.c_str()));
}

编辑:你也没有实现的重载

virtual void log(int debugLevel, char* fmt, ...) = 0;

请注意,尽管使用const_cast是一个非常糟糕的主意并且是未定义的行为。您可以通过执行以下操作来获得明确定义的行为:

virtual void log(string logText, int debugLevel, string /*threadname*/)
{
    logText.push_back('\0'); // Add null terminator
    Log(&logText[0]); // Send non-const string to function
    logText.pop_back(); // Remove null terminator
}

更好的是,首先使“Log” const-correct。

于 2010-07-06T12:01:29.920 回答
1

通过从您那里派生您的DLog类,Logger可以确保您将为DLog基类中声明的所有纯虚拟方法(假设您不希望作为抽象类)提供实现。在这里,您没有为纯虚函数提供实现,因此类DLog变成了抽象类。在 C++ 中,您不能创建抽象类的实例,因此会出现编译器错误。顺便说一句,您的基类缺少虚拟析构函数。

于 2010-07-06T12:04:52.917 回答