static_cast问题
在MSDN中看了有关这个操作符的解释,有些地方不太明白,大家给解释一下:
class B {};
class D : public B {};
void f(B* pb, D* pd) {
D* pd2 = static_cast<D*>(pb); // not safe, pb may
// point to just B
B* pb2 = static_cast<B*>(pd); // safe conversion
}
In contrast to dynamic_cast, no run-time check is made on the static_cast conversion of pb. The object pointed to by pb may not be an object of type D, in which case the use of *pd2 could be disastrous. For instance, calling a function that is a member of the D class, but not the B class, could result in an access violation.
红色的地方为什么那样解释呢,既然已经类型装换了,为什么不可以调用D中的呢
[解决办法]
pb是B指针,强转为D后调用一个B没有的D中的函数会出错
第二种就不会,因为pd是D的指针,D继承自B
[解决办法]
子类是有父类的所有东西的
所以向上转型是安全的