是的,C++析構(gòu)函數(shù)支持虛析構(gòu)。在C++中,當(dāng)一個類被設(shè)計為基類時,并且這個類有虛函數(shù),那么它的析構(gòu)函數(shù)也應(yīng)該是虛的。這是為了確保當(dāng)通過一個基類指針刪除一個派生類對象時,能夠正確地調(diào)用派生類的析構(gòu)函數(shù),從而避免資源泄漏。
以下是一個包含虛析構(gòu)函數(shù)的基類示例:
#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; // 調(diào)用的是派生類的析構(gòu)函數(shù),然后是基類的析構(gòu)函數(shù)
return 0;
}
輸出結(jié)果:
Base constructor called
Derived constructor called
Derived foo function called
Base destructor called
Derived destructor called
在這個例子中,基類Base
有一個虛析構(gòu)函數(shù),派生類Derived
繼承自Base
并重寫了foo()
函數(shù)。在main()
函數(shù)中,我們通過基類指針ptr
刪除派生類對象,這時會先調(diào)用派生類的析構(gòu)函數(shù),然后調(diào)用基類的析構(gòu)函數(shù)。