问题描述
我有以下类,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.
我如何解决这个错误?
我猜这是因为没有两个纯虚拟函数都没有在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 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;
。你必须实现它,因为它是基类中的纯虚拟。
has not been implemented in class DLog. You have to implement it because it's pure virtual in the base class.
你可能意味着在你的第一个重载 log
在 DLog
:
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('\0'); // Add null terminator
Log(&logText[0]); // Send non-const string to function
logText.pop_back(); // Remove null terminator
}
正确的第一。
这篇关于纯虚函数和抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!