当前位置: 首页 > 工具软件 > Fast-cast > 使用案例 >

Static_cast & Dynamic_cast

糜运良
2023-12-01

static_cast:

  1. Conversions between integers, float, double, char and etc.

balance = static_cast<double>(cents);
char c;//0 <= c <= 10
digit = static_cast<int>(c) - static<int>('0');
  1. Downcast a base class pointer to a derived class pointer. It is fast and efficient(compile time), but it may crush if you do anything wrong. It is safer to use dynamic_cast.

//This is approved
​
Vehicle *p_vehicle = new Car("Ford", 2012);
Car* p_car = static_cast<Car*>(p_vehicle);
Car* p_car = dynamic_cast<Car*>(p_vehicle);
​
//This is not right
Vehicle *p_vehicle = new vehicle;
Car* p_car = static_cast<Car*>(p_vehicle);
//because a derived class belongs to the base class, but the base class does not belong to the derived class

Both p_car and p_vehicle contains the same memory address value. However it is the type of the variable that dictates which function the variable can do, not the variable's address value.

Dynamic_cast:

When function is declared as virtual in the base class, then the corresponding functions in the derived class will be declared as virtual too. But it is a good habit to add virtual in front of the functions in the derived class too.

down cast a base class pointer to a derived class pointer.

typical use:

Zebra * p_zebra = nullptr;
​
Elephant * p_elephant = nullptr;
​
Tiger * p_tiger = nullptr
​
Panda * p_panda  = nullptr;
​
for  ( int i = 0 ; i < kAnimalMax; i++ ) {
​
          // generic processing
​
         zoo[i]->Eat ( );
​
        zoo[i]->Drink ( );
​
        // specific processing
​
       if  ( (p_zebra = dynamic_cast <Zebra *> (zoo[i]))  != nullptr) {
​
              p_zebra->NibbleHair ( );
​
       } else if ((p_elephant = dynamic_cast <Elephant *> (zoo[i]))  != nullptr) {
​
                          p_elephant->Grumbling ( );
​
      } else if ((p_tiger = dynamic_cast <Tiger *> (zoo[i]))  != nullptr) {
​
                       p_tiger->Hunt ( );
​
       } else if ((p_panda= dynamic_cast <Panda *> (zoo[i]))  != nullptr) {
​
                          p_panda->JustSleep ( );
​
       }
​
} // end of for loop

When dynamic_cast a pointer, if the pointer is not that kind of pointer, it will yield nullptr. So, it is a great way to distinguish different types of pointer like above. You do not need to use dynamic_cast in all polymorphism.

PS. Some of the codes are from Foothill college CS2B Professor Tri Pham class. Awesome professor. I wrote this article because I am kind of confused of these two different cast in his class. I will delete the codes if I violate the copyright. 

 类似资料: