一:首先是做同类型的类进行转换。有同一个基类的几个子类应用虚函数可以达到动态指定的效果

输出:

----------------------

     DerivedOne::foo()

   DerivedTwo::foo()

    

-----------------------

 

 

#include <iostream>
#include <string>
#include  <cmath>
#include  <fstream>
using namespace std;
class Base {
public:
   virtual ~Base() {}
};

class Fooer {
public:
   virtual void foo(){};
};

class DerivedOne :  public Fooer {
public:
   void foo() { cout << "DerivedOne::foo()\n"; }
};

class DerivedTwo : public Fooer {
public:
   void foo() { cout << "DerivedTwo::foo()\n"; }
};

class DerivedThree: public Fooer{
};

int main() {
   Fooer* bps[3];
   bps[0] = new DerivedOne();
   bps[1] = new DerivedTwo();
   bps[2] = new DerivedThree();

   for ( int i = 0; i < 3; ++i ) {
      Fooer* thisOne = dynamic_cast<Fooer*>( bps[i] );
      if ( thisOne )
         thisOne->foo();
        else{
            cout<<"nothing"<<endl;
        }
   }
}