Posted on 2010-05-12 16:31
S.l.e!ep.¢% 阅读(565)
评论(0) 编辑 收藏 引用 所属分类:
C++
前两天写了个程序,发生了异常,调试了半天发现是dynamic_cast,的异常
class A{........}
class B:public A{......}
int main()
{
A *a = new B;
B *p = dynamic_cast<B*> a //结果这里抛出了异常
}
找了半天的资料,理论是是可以的啊
MSDN上关于向下转型的解释:
If the type of expression is a base class of the type of type-id, a run-time check is made to see if expression actually points to a complete object of the type of type-id. If this is true, the result is a pointer to a complete object of the type of type-id. For example:
class B { ... };
class D : public B { ... };
void f()
{
B* pb = new D; // unclear but ok
B* pb2 = new B;
D* pd = dynamic_cast<D*>(pb); // ok: pb actually points to a D
...
D* pd2 = dynamic_cast<D*>(pb2); // pb2 points to a B not a D
// cast was bad so pd2 == NULL
...
}
This type of conversion is called a "downcast" because it moves a pointer down a class hierarchy, from a given class to a class derived from it.
最后发现原来vc6.0要支持向下转型要加入GR开关,而这在vc6.0z中是默认关闭的
基础很重要....哎