gpt4 book ai didi

C++ - 虚拟析构函数和链接器错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:05:04 27 4
gpt4 key购买 nike

我得到了我编写的这个界面:

#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

这些方法是纯虚拟的,因此必须通过派生类来实现。如果我尝试创建一个继承此接口(interface)的类,我会收到以下链接器错误:

Undefined reference to ILog::ILog
Undefined reference to ILog::~ILog

我明白为什么有一个虚拟析构函数(以确保派生的析构函数被调用)但我不明白为什么我会收到此链接器错误。

编辑:好的,所以我还需要定义虚拟析构函数。但是我仍然可以在虚拟析构函数的定义中执行某些操作,还是它会简单地调用我的派生类析构函数并跳过它?比如,这会触发:

virtual ~ILog() { delete monkey; }

最佳答案

你还没有定义构造函数和析构函数,你只是声明了它们

尝试

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;
};
  • 构造函数:一旦你声明了一个构造函数,任何构造函数,编译器都不会为你生成一个默认的构造函数。派生类的构造函数试图调用接口(interface)的构造函数,它没有定义,只是声明了。要么提供定义,要么删除声明
  • 析构函数:其他考虑因素(例如,与上述类似的考虑因素)你的析构函数是虚拟的。每个非纯虚函数必须有一个定义(因为根据定义使用)。

can I still perform stuff in the definition of the virtual destructor, or will it simply call my derived classes destructor and skip it? Like, will this trigger

是的,你可以。当调用派生类的析构函数时,会自动调用基类的析构函数。但是,我认为在接口(interface)的析构函数中做的事情没有什么意义。但从技术上讲,您可以在析构函数中执行任何操作,即使它是虚拟的也是如此

关于C++ - 虚拟析构函数和链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8609880/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com