«
用父类指针释放子类对象,不能调用子类析构函数 解决方法

时间:2023-5-12    作者:范文泉    分类: 编程


/*
父类引用指向子类对象时,用父类指针释放子类对象,将不能调用子类析构函数
解决方法:
将父类析构函数改为 虚析构 或 纯虚析构

虚析构:
virtual ~Animal() {
        cout << "Animal 析构" << endl;
    }

纯虚析构:
virtual ~Animal() = 0;
类外实现
Animal::~Animal() {
    cout << "Animal xigou" << endl;
}
*/

class Animal {
public:
    Animal() {
        cout << "Animal gouzao" << endl;
    }
    virtual void getup() = 0;
    virtual void wash() = 0;
    virtual void study() = 0;
    virtual void sleep() = 0;
    void live() {
        getup();
        wash();
        study();
        sleep();
    }

    virtual ~Animal() = 0;//纯虚析构,必须在类外实现
};

Animal::~Animal() {
    cout << "Animal xigou" << endl;
}

class Cat :public Animal{
public:
    Cat(int a) {
        this->age = new int(a);
        cout << "Cat gouzao" << endl;
    }
    virtual void getup() {
        cout << "cat get up" << endl;
    }
    virtual void wash() {

        cout << "cat go to wash" << endl;
    }
    virtual void study()
    {
        cout << "cat is studying" << endl;
    }
    virtual void sleep()
    {
        cout << "cat go to bed" << endl;
    }

    int* age;
    ~Cat() {
        cout << "Cat xigou" << endl;
        if (age != NULL) {
            delete age;
            age = NULL;
        }
    }

};

class Dog :public Animal {
public:

    virtual void getup() {
        cout << "dog get up" << endl;
    }
    virtual void wash() {

        cout << "dog go to wash" << endl;
    }
    virtual void study()
    {
        cout << "dog is studying" << endl;
    }
    virtual void sleep()
    {
        cout << "dog go to bed" << endl;
    }

};

void life(Animal * animal) {
    animal->live();
    delete animal;
}

void test() {
    life(new Cat(10));
    life(new Dog);
}

int main() {
    test();
}