是的,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
刪除派生類對象,這時會先調用派生類的析構函數,然后調用基類的析構函數。