正确的方式继承从一个虚拟类与非虚拟父 [英] Correct way to inherit from a virtual class with non-virtual parent
问题描述
我写了这个测试代码,使用三种类型: struct One
是一个没有虚拟成员的普通类型, struct Two:One
有一个纯虚函数和一个虚析构函数, struct Three:Two implements
两个
I've written this test code that uses three types: struct One
is a normal type with no virtual members, struct Two : One
has a pure virtual function and a virtual destructor, and struct Three : Two
implements Two
's interface.
#include <iostream>
struct One
{
~One() {
std::cout << "~One()\n";
}
};
struct Two : One
{
virtual ~Two() {
std::cout << "~Two()\n";
}
virtual void test() = 0;
};
struct Three : Two
{
virtual ~Three() {
std::cout << "~Three()\n";
}
virtual void test() {
std::cout << "Three::test()\n";
}
};
int main()
{
Two* two = new Three;
two->test();
One* one = two;
delete one;
}
不出所料,输出为
Three :: test()
〜One()
Three::test()
~One()
有没有办法解决这个问题,而不是使每个析构函数虚拟?或者应该程序员只是小心不要遇到这种情况?我发现很奇怪,编译这个时没有警告。
Is there any way to fix this other than making every destructor virtual? Or should programmers just be careful not to run into this situation? I find it odd that there's no warning when compiling this.
推荐答案
唯一的修复不是通过指向 c $ c>。
The only "fix" is not to delete the objects through a pointer to One
.
如果这是一个常见的问题,或者不是,这取决于你的类是如何使用的。例如,标准库包含没有虚拟析构函数的 unary_function
结构,但我们几乎看不到这样的误用。
If this is a frequent problem, or not, depends on how your classes are used. For example, the standard library contains structs like unary_function
without a virtual destructor, but we hardly ever see it misused like this.
这篇关于正确的方式继承从一个虚拟类与非虚拟父的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!