#include <iostream>
using namespace std ;class Base {
public:
virtual void f() {
cout << "Inside Base\n" ;
}
};class Derived:public Base{
public:
void f() {cout << "Inside Derived\n" ;
}
};int main()
{
Base *bp,b_ob ;
Derived *dp,d_ob ; dp = dynamic_cast<Derived *> (&d_ob) ;
if (dp)
{
cout << "Cast from Derived * to Derived * Ok.\n" ;
dp->f() ;
}
else
cout << "Error\n" ;
cout << endl ;

bp = dynamic_cast<Base *> (&d_ob) ;
if(bp) {
cout << "Cast from Derived * to Base * OK.\n" ;
bp->f() ;
}
else
cout << "Error\n" ; cout << endl ; bp = dynamic_cast<Base *> (&b_ob) ;
if (bp)
{
cout << "Cast from Base * to Base * OK.\n" ;
bp->f() ;
}
else
cout << "Error\n" ; cout << endl ; dp = dynamic_cast<Derived *> (&b_ob) ;
if (dp)
{
cout << "Error\n" ;
}
else
cout << "Cast from Base* to Derived * not OK.\n" ;
cout << endl ; bp = &d_ob ;
dp = dynamic_cast<Derived *> (bp) ;
if (dp)
{
cout << "Casting bp to a Derived * OK\n" <<
"because bp is really pointing\n" << 
"to a Derived object.\n" ;
dp->f() ;
}
else
cout << "Error\n" ; cout << endl ; bp = &b_ob ;
dp = dynamic_cast<Derived *> (bp) ;
if (dp)
cout << "Error" ;
else
{
cout << "Now casting bp to a Derived *\n " 
 << "is not OK because bp is really \n" 
 << "pointing to a Base object.\n" ;
} cout << endl ; dp = &d_ob ;
bp = dynamic_cast<Base *> (dp) ;
if(bp)
{
cout << "Casting dp to a Base * is OK.\n" ;
bp->f() ;
}
else
cout << "Error\n" ; return 0 ;
}请C++的高手赐教.

解决方案 »

  1.   

    我在codeblock+mingw3.4.2下编译通过,没有出现你说的运行时错误。
    输出结果如下:
    Cast from Derived * to Derived * Ok.
    Inside DerivedCast from Derived * to Base * OK.
    Inside DerivedCast from Base * to Base * OK.
    Inside BaseCast from Base* to Derived * not OK.Casting bp to a Derived * OK
    because bp is really pointing
    to a Derived object.
    Inside DerivedNow casting bp to a Derived *
     is not OK because bp is really 
    pointing to a Base object.Casting dp to a Base * is OK.
    Inside Derived另外:
    dp = dynamic_cast <Derived *> (&b_ob) ;
    有以下warning
    |54|warning: dynamic_cast of `Base b_ob' to `class Derived*' can never succeed|
      

  2.   

    我的是在Mircrosoft VC++ 6.0里面编译运行的的,为什么在这边就运行出错