使用基类指针创建对象时,缺少派生类析构函数
Missing Derived class Destructor when object is created with the base class pointer
在下面的代码示例中,没有调用派生类析构函数。知道为什么吗?我有一个基类,它具有虚拟函数。现在我使用基类指针来创建派生类的新对象。我的理解是,当派生类对象被销毁时,首先调用派生类的析构函数,然后调用基类。然而,我只看到基类的析构函数被调用。有人知道我做错了什么吗?或者我对c++的理解哪里不正确?
#include <iostream>
#include <bitset>
using namespace std;
class DomesticAnimals
{
public:
DomesticAnimals() {
cout <<"Domestic Animal Base" <<endl;
};
~DomesticAnimals() {
cout <<"Domestic Animal kill " <<endl;
};
virtual void Speak() = 0;
virtual void EatFood()= 0;
virtual int NoOfLegs() {
return 4;
} ;
};
class Cat : public DomesticAnimals
{
public:
Cat();
~Cat();
void Speak() override;
void EatFood() override;
};
Cat::Cat()
{
cout << "Kat was born" << endl;
}
Cat:: ~Cat()
{
cout << "Kill de Cat" << endl;
}
void Cat:: Speak()
{
cout << "Meow Meow " << endl;
}
void Cat::EatFood()
{
cout <<"Kat eet de muis vandaag !! " <<endl;
}
class Dog : public DomesticAnimals
{
public:
Dog();
~Dog();
void Speak() override;
void EatFood() override;
};
Dog::Dog()
{
cout << "A puppy was born" << endl;
}
Dog::~Dog()
{
cout << "Kill de hond" << endl;
}
void Dog :: Speak()
{
cout <<"bow bow woof woof" <<endl;
}
void Dog :: EatFood()
{
cout << "de hond eet een kip voor middageten" <<endl;
}
void DogActions()
{
DomesticAnimals* dog = new Dog;
cout<< endl;
dog->Speak();
dog->EatFood();
cout<<"No of legs for dog = "<< dog->NoOfLegs() <<endl;
cout<<endl;
delete dog;
dog = NULL;
}
void CatActions()
{
DomesticAnimals* cat = new Cat;
cat->Speak();
cat->EatFood();
cout<<"No of legs for cat = "<< cat->NoOfLegs() << endl;
delete cat;
cat = NULL;
}
int main(void)
{
DogActions();
CatActions();
return 0;
}
程序的输出如下
Domestic Animal Base
A puppy was born
bow bow woof woof
de hond eet een kip voor middageten
No of legs for dog = 4
Domestic Animal kill
Domestic Animal Base
Kat was born
Meow Meow
Kat eet de muis vandaag !!
No of legs for cat = 4
Domestic Animal kill
基类的析构函数需要是虚拟的:
virtual ~DomesticAnimals() {
cout << "Domestic Animal kill" << endl;
};
为了避免任何混淆(请参阅注释(:只有在通过指向基类的指针删除对象的情况下,才需要使析构函数成为虚拟的。当需要多态性时,通常会出现这种情况。
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 添加自定义析构函数时,Move 构造函数在派生类中消失
- 从 c++ 中派生类的析构函数调用虚函数
- 如何从 Gtk::窗口调用派生对象的析构函数
- 在派生类中将公共父析构函数设为私有
- 即使基类和派生类只使用基元数据类型,我是否需要定义虚拟析构函数
- C++11:我可以显式调用基类析构函数来销毁派生类吗
- 在从仅移动类型派生的类中定义析构函数在使用 std::vector emplace_back或push_back创建时会
- 受保护的析构函数禁用在堆栈上创建派生类的对象?
- 防止派生析构函数中的 vtable 数据争用
- 如何在另一个类的向量中调用派生类的析构函数
- 了解派生类中C++析构函数的行为
- 私有派生析构函数
- 在派生类中重写哪个基类的虚拟析构函数
- 基类没有析构函数,但派生类有析构函数。我是否需要寻找与堆无关的任何陷阱?
- 显式声明派生类中所需的析构函数
- 调用派生类的析构函数
- 在这种情况下,我的派生类是否还需要一个虚拟析构函数
- g++对基类析构函数和派生类指针的未定义引用
- 基析构函数如何调用派生析构函数