请教:dynamic_cast和static_cast的区别的一个例子
Bjarne Stroustrup写的哦。
dynamic_cast和static_cast的区别的一个例子,但是文中"if pb points to a B (only)"是什么意思?
class B { /* ... */ };
class D : public B { /* ... */ };
void f(B* pb)
{
D* pd1 = dynamic_cast<D*>(pb);
D* pd2 = static_cast<D*>(pb);
}
If pb really points to a D then pd1 and pd2 get the same value. Similarly, if pb==0 both pd1 and pd2 become 0. However, if pb points to a B (only) then dynamic_cast will know enough to return 0 whereas static_cast must rely on the programmer’s assertion that pb points to a D and return a pointer
to the supposed D object.