在C++中,如果我没有将析构函数声明为虚函数,是否仍然可以将非多态基类的指针/引用向下转换?
虚拟析构函数与向下转型关系不大。将析构函数设为虚拟的目的是为了通过基类指针安全删除对象。
Base * ptr = new Derived;
delete ptr; // undefined behavior if Base destructor isn't virtual
可以使用static_cast
进行向下转型,但需自行承担责任。
void processBase(Base * ptr)
{
// undefined behavior if ptr does not point to Derived
// object or some object that inherits from Derived
Derived * derived = static_cast<Derived *>(ptr);
}
此外,还有dynamic_cast
,它将检查向下转型是否合法,但需要转型的表达式指向(或引用)一个多态对象(即至少声明或继承一个虚函数的对象)。
5.2.7.6否则,v应为多态类型的指针或左值(10.3)
如果转型表达式的类型不是多态的,则程序将无法编译。
总结一下 - 使析构函数为虚函数将使您的类变成多态类,但声明任何其他虚成员函数也会实现相同的效果。要使用dynamic_cast
,您需要一个多态类型。
dynamic_cast
向下转换是不合法的。 - Oktalist
dynamic_cast
是不可能的。 - Some programmer dude