类具有虚拟功能和可访问的非虚拟析构函数 [英] class has virtual functions and accessible non-virtual destructor
问题描述
我有两节课:
class A {
public:
virtual void somefunction() = 0;
};
class B : public A {
public:
B();
~B();
void somefunction();
};
B::B() {}
void B::somefunction() {
// some code
}
但是使用g ++会出现错误:
But with g++ I get errors:
class A has virtual functions and accessible non-virtual destructor
class B has virtual functions and accessible non-virtual destructor
我不知道这个错误是什么...在博客的某个地方,我读到这是一个编译器警告.我该如何解决该问题?
I don't have any idea what this error is... Somewhere on blogs I read that it's a compiler warning. How can I fix the problem?
推荐答案
之所以会发生这种情况,是因为您的基类A
没有虚拟析构函数.例如,如果您有以下代码:
This happens because your base class A
does not have a virtual destructor. For instance, if you had this code:
int main()
{
A* a = new B;
delete a;
}
然后,由于A
不是虚拟的,因此delete a
调用将无法调用B
的析构函数. (这会泄漏B
的所有资源.)您可以在此处详细了解虚拟析构函数.
Then the delete a
call would not be able to call B
's destructor because A
's isn't virtual. (It would leak all of B
's resources.) You can read more about virtual destructors here.
在基类中添加一个虚拟析构函数,您应该没事.
Add a virtual destructor to your base class and you should be fine.
class A
{
public:
virtual void somefunction() = 0;
virtual ~A() = 0;
}
这篇关于类具有虚拟功能和可访问的非虚拟析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!