温馨提示×

C++析构函数支持虚析构吗

c++
小樊
81
2024-11-09 00:45:28
栏目: 编程语言

是的,C++析构函数支持虚析构。在C++中,当一个类被设计为基类时,并且这个类有虚函数,那么它的析构函数也应该是虚的。这是为了确保当通过一个基类指针删除一个派生类对象时,能够正确地调用派生类的析构函数,从而避免资源泄漏。

以下是一个包含虚析构函数的基类示例:

#include <iostream>

class Base {
public:
    Base() {
        std::cout << "Base constructor called" << std::endl;
    }

    virtual ~Base() {
        std::cout << "Base destructor called" << std::endl;
    }

    virtual void foo() {
        std::cout << "Base foo function called" << std::endl;
    }
};

class Derived : public Base {
public:
    Derived() {
        std::cout << "Derived constructor called" << std::endl;
    }

    ~Derived() {
        std::cout << "Derived destructor called" << std::endl;
    }

    void foo() override {
        std::cout << "Derived foo function called" << std::endl;
    }
};

int main() {
    Base* ptr = new Derived();
    ptr->foo();
    delete ptr; // 调用的是派生类的析构函数,然后是基类的析构函数
    return 0;
}

输出结果:

Base constructor called
Derived constructor called
Derived foo function called
Base destructor called
Derived destructor called

在这个例子中,基类Base有一个虚析构函数,派生类Derived继承自Base并重写了foo()函数。在main()函数中,我们通过基类指针ptr删除派生类对象,这时会先调用派生类的析构函数,然后调用基类的析构函数。

0