Kai*_*aan 4 c++ inheritance linker abstract-class
我得到了这个我写过的界面:
#ifndef _I_LOG_H
#define _I_LOG_H
class ILog {
public:
ILog();
virtual ~ILog();
virtual void LogInfo(const char* msg, ...) = 0;
virtual void LogDebug(const char* msg, ...) = 0;
virtual void LogWarn(const char* msg, ...) = 0;
virtual void LogError(const char* msg, ...) = 0;
private:
Monkey* monkey;
};
#endif
Run Code Online (Sandbox Code Playgroud)
这些方法是纯虚拟的,因此必须通过派生类来实现.如果我尝试创建一个继承此接口的类,我会收到以下链接器错误:
Undefined reference to ILog::ILog
Undefined reference to ILog::~ILog
Run Code Online (Sandbox Code Playgroud)
我理解为什么有一个虚拟析构函数(为了确保派生的析构函数被调用),但我不明白为什么我会得到这个链接器错误.
编辑:好的,所以我也需要定义虚拟析构函数.但是我仍然可以在虚拟析构函数的定义中执行某些操作,还是只调用我的派生类析构函数并跳过它?喜欢,这会触发:
virtual ~ILog() { delete monkey; }
Run Code Online (Sandbox Code Playgroud)
Arm*_*yan 10
您还没有定义构造函数和析构函数,您只声明了它们
尝试
class ILog {
public:
//note, I want the compiler-generated default constructor, so I don't write one
virtual ~ILog(){} //empty body
virtual void LogInfo(const char* msg, ...) = 0;
virtual void LogDebug(const char* msg, ...) = 0;
virtual void LogWarn(const char* msg, ...) = 0;
virtual void LogError(const char* msg, ...) = 0;
};
Run Code Online (Sandbox Code Playgroud)
我仍然可以在虚拟析构函数的定义中执行操作,还是只调用我的派生类析构函数并跳过它?就像,这会触发
是的你可以.当调用派生类的析构函数时,它将自动调用基类的析构函数.然而,我无法想到在接口的析构函数中进行操作是有意义的.但从技术上讲,你可以在析构函数中做任何事情,即使它是虚拟的