我有以下类,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/