C++ 中的 Dynamic_cast 和 static_cast


static_cast:這用於正常的型別轉換。這還負責隱式型別強制轉換的 cast,還可以顯式地呼叫。您應該在諸如將浮點轉換為 int、char 轉換為 int 等情況下使用它。這可以轉換相關的型別類。如果型別不同,它將生成一些錯誤。

示例

#include<iostream>
using namespace std;
class Base {};
class Derived : public Base {};
class MyClass {};
main(){
   Derived* d = new Derived;
   Base* b = static_cast<Base*>(d); // this line will work properly
   MyClass* x = static_cast<MyClass*>(d); // ERROR will be generated during compilation
}

輸出

[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'

dynamic_cast:這個 cast 用於處理多型。只有在轉換為派生類時才需要使用它。在從基類轉換為派生類時,專門用於繼承中。

示例

#include<iostream>
using namespace std;
class MyClass1 {
   public:
      virtual void print()const {
         cout << "This is from MyClass1\n";
      }
};
class MyClass2 {
   public:
      virtual void print()const {
         cout << "This is from MyClass2\n";
      }
};
class MyClass3: public MyClass1, public MyClass2 {
   public:
      void print()const {
         cout << "This is from MyClass3\n";
      }
};
int main(){
   MyClass1* a = new MyClass1;
   MyClass2* b = new MyClass2;
   MyClass3* c = new MyClass3;
   a -> print();
   b -> print();
   c -> print();
   b = dynamic_cast< MyClass2*>(a); //This cast will be failed
   if (b)
      b->print();
   else
      cout << "no MyClass2\n";
   a = c;
   a -> print(); //Printing from MyClass3
   b = dynamic_cast< MyClass2*>(a); //Successfully casting is done
   if (b)
      b -> print();
   else
      cout << "no MyClass2\n";
}

輸出

This is from MyClass1
This is from MyClass2
This is from MyClass3
no MyClass2
This is from MyClass3
This is from MyClass3

更新於:2019 年 7 月 30 日

3 千次以上檢視

開啟您的 事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.