c++ - virtual destrutors vs normal methods in C++
问题描述
Consider the following three programs in C++:
program 1
struct base{
virtual ~base() =0;
};
struct derived: public base{
~derived();
};
derived::~derived(){}
int main(){}
program 2
struct base{
virtual ~base() =0;
};
struct derived: public base{
~derived(){}
};
int main(){}
program 3
struct base{
virtual void func() =0;
};
struct derived: public base{
void func();
};
void derived::func(){}
int main(){}
The programs #2 and #3 compile and run fine however the first gives the following error:
Undefined symbols for architecture x86_64: "base::~base()", referenced from: derived::~derived() in main-d923b9.o ls: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
I'd like to know why I am unable to define virtual destructors outside of the class definition however I am able to do it inside the class definition. Additionally I can define methods outside the class, just not destructors.
解决方案
这是错误的
struct base{
virtual ~base() =0;
};
因为base::~base
没有定义。即使它已被声明为纯虚拟,也需要对其进行定义(在类之外,没有语法方法可以将函数声明为纯虚拟并内联定义),因此derived
可以从中继承:
struct base
{
virtual ~base() = 0;
};
base::~base() {}
我想知道为什么我无法在类定义之外定义虚拟析构函数
好吧,你可以:我刚刚做到了。
那么,为什么要实现一个~base
已经声明为纯虚函数()?
由于derived
继承自base
,当一个类型的对象derived
被破坏时,它必然调用base
' 的析构函数。这就是继承的工作方式。从某种意义上说,derived::~derived
需要与base::~base
. 即使base::~base
是纯虚拟的(意味着继承自的类base
不是完整的类型,除非它定义了析构函数)它需要被定义以便~derived
找到它并且链接器变得快乐。
推荐阅读
- python - 过滤在一列中占 X% 值的数据框行
- laravel - 如何使用 Laravel 更新多条记录?
- mysql - Mysql 不会创建结束日期在 2038-01-19 之后的 EVENT
- python - ModuleNotFoundError:没有名为“flask_weasyprint”的模块
- javascript - JSON - 无效的令牌
- ios - 从 Viewcontroller 保存 3 张图像
- python - 如何将字符串中的base64值更改为字节?
- google-apps-script - 无论如何执行托管在 GHE 上的 Google App 脚本代码
- javascript - 如何从 iframe 关闭 Apex 模态页面?
- angular - 在 Scroll 上动态加载 IONIC 列表的数据