繁体   English   中英

使用基本 class 指针创建 object 时缺少派生 class 析构函数

[英]Missing Derived class Destructor when object is created with the base class pointer

在以下代码示例中,未调用派生的 class 析构函数。 知道为什么吗? 我有一个具有虚拟功能的基础 class。 现在我使用基本 class 指针来创建派生 class 的新对象。 我的理解是,当派生的 class 对象被销毁时,派生的 class 的析构函数首先被调用,然后是基础 class。 但是,我只看到调用了基础 class 的析构函数。 有谁知道我做错了什么或者我对 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;
}

程序的output如下

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 

基础 class 的析构函数需要是虚拟的:

virtual ~DomesticAnimals() {
    cout << "Domestic Animal kill" << endl;
};

为了避免任何混淆(见注释):只有在 object 通过指向其基础 class 的指针删除的情况下,才需要使析构函数为虚拟。 这通常是需要多态性的情况。

暂无
暂无

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

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