简体   繁体   English

C++ 删除继承的 class

[英]C++ deleting inherited class

Let's say there is a class Object and then another class Cat that inherits Object .假设有一个 class Object然后另一个 class Cat继承了 Z497031794014A5525435B3 Next, there is a list of Object * (pointers).接下来是Object *(指针)的列表。 Then, I create a new Cat and put it into the list.然后,我创建了一个新的Cat并将其放入列表中。 After some time I want to delete all Cats and call delete on each member of the list.一段时间后,我想删除所有Cats并在列表的每个成员上调用delete Does it call destructor of Cat ?它是否调用Cat的析构函数?

Yes if you marked the destructor of object as virtual.是的,如果您将 object 的析构函数标记为虚拟。

class Object {
  public:
  virtual ~Object(){} //make the base class destructor virtual
};

class cat : public Object {
  public:
  virtual ~cat(){} // now this gets called when a pointer to Object that is a cat is destroyed
}

If the destructor of Object is virtual, yes.如果 Object 的析构函数是虚拟的,是的。

What you describe is precisely the situation where virtual destructors come in. Read the C++ FAQ .您所描述的正是虚拟析构函数进入的情况。阅读 C++常见问题解答

Yes, if class Object (the base class) destructor is declared virtual, otherwise you run into undefined behavior which you don't want.是的,如果class Object (基类)析构函数被声明为虚拟的,否则您会遇到您不想要的未定义行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM