Posted on 2010-05-12 16:31
S.l.e!ep.¢% 閱讀(568)
評論(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中是默認關閉的
基礎很重要....哎