纯虚函数和抽象类 [英] pure virtual function and abstract class
问题描述
我有以下类,Base 和 Derived,当我编译时,编译器抱怨它无法创建 DLog 的实例,因为它是抽象的.
I have the following classes, Base and Derived and when I compile the compiler complains that it cannot create an instance of DLog because it is abstract.
谁能告诉我如何解决这个错误?
Can someone tell me how I can fix this error?
我猜这是因为不是两个纯虚函数都没有在 Derived 中实现.
I'm guessing it's because not both pure virtual functions are not implemented in the 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 instantion as a singleton
DLog *DLog::Instance()
{
if (!m_instance)
m_instance = new DLog();
return m_instance;
}
推荐答案
virtual void log(string logText, int debugLevel, string threadName = "") = 0;
尚未在 DLog 类中实现.您必须实现它,因为它在基类中是纯虚拟的.
has not been implemented in class DLog. You have to implement it because it's pure virtual in the base class.
您可能是在 DLog
中第一次重载 log
时的意思:
You probably meant this in your first overload of log
in 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
是一个非常糟糕的主意并且是未定义的行为.您可以通过执行以下操作来获得明确定义的行为:
Note here though that using the const_cast
is a very bad idea and is undefined behavior. You can get well defined behavior by doing something like this instead:
virtual void log(string logText, int debugLevel, string /*threadname*/)
{
logText.push_back(' '); // Add null terminator
Log(&logText[0]); // Send non-const string to function
logText.pop_back(); // Remove null terminator
}
不过更好的是,首先将Log"设置为常量.
Better yet though, just make "Log" const-correct in the first place.
这篇关于纯虚函数和抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!