c++ - 纯虚函数和抽象类

标签 c++ abstract-class pure-virtual

我有以下类,Base 和 Derived,当我编译时编译器提示它不能创建 DLog 的实例,因为它是抽象的。

谁能告诉我如何解决这个错误?

我猜这是因为不是两个纯虚函数都没有在 Derived 中实现。

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;
}

最佳答案

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

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

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

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”成为常量正确的。

关于c++ - 纯虚函数和抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3185954/

相关文章:

java - 为什么java.awt.Graphics类在java中是抽象的?

C++:纯虚函数 f 的参数 x 是否可以在 f 的派生类实现中替换为 x 的子类型?

c++ - 运行时错误 : addition of unsigned offset

c++ - 在 C 窗口中将参数传递给线程的最佳方法是什么?

java - 没有方法的抽象类

java - 选择接口(interface)或抽象类

c++ - undefined symbol "vtable for ..."和 "typeinfo for..."?

C++ 无法覆盖纯虚函数

C++ 从一个文件中一次性填充一个类

c++ - 管理 C++ 单精度和 double 混合计算的规则是什么?