多型型別 - 臨時、包含、引數化和強制轉換


本文中,我們將探討不同型別的多型性。

  • 臨時多型性
  • 包含多型性
  • 引數化多型性
  • 強制轉換多型性

臨時多型性被稱為“過載”。這可以讓具有相同名稱的方法根據不同型別採取不同的行為。函式和運算子都可以被過載。一些語言不支援運算子過載,但函式過載卻很常見。

示例

#include<iostream>
using namespace std;
int add(int a, int b) {
   return a + b;
}
string add(string a, string b) {
   return a + b; //concatenate
}
int main() {
   cout << "Addition of numbers: " << add(2, 7) << endl;
   cout << "Addition of Strings: " << add("hello", "World") << endl;
}

輸出

Addition of numbers: 9
Addition of Strings: helloWorld

包含多型性被稱為“子型別化”。這允許使用基類指標和引用來指向派生類。這是執行時多型性。在我們執行物件之前,我們並不知道實際物件的型別。我們需要使用 C++ 中的虛擬函式來實現這種包含多型性。

示例

#include<iostream>
using namespace std;
class Base {
   public:
      virtual void print() {
         cout << "This is base class." << endl;
      }
};
class Derived : public Base {
   public:
      void print() {
         cout << "This is derived class." << endl;
      }
};
int main() {
   Base *ob1;
   Base base_obj;
   Derived derived_obj;
   ob1 = &base_obj; //object of base class
   ob1->print();
   ob1 = &derived_obj; //same pointer to point derived object
   ob1->print();
}

輸出

This is base class.
This is derived class.

強制轉換多型性被稱為“型別轉換”。當某個物件或基本型別被轉換為其他型別時,就會發生這種型別多型性。有兩種型別的轉換。隱式轉換是由編譯器自身執行的,而顯式轉換則是使用 const_cast、dynamic_cast 等執行的。

示例

#include<iostream>
using namespace std;
class Integer {
   int val;
   public:
      Integer(int x) : val(x) {
   }
   operator int() const {
      return val;
   }
};
void display(int x) {
   cout << "Value is: " << x << endl;
}
int main() {
   Integer x = 50;
   display(100);
   display(x);
}

輸出

Value is: 100
Value is: 50

引數化多型性被稱為“早期繫結”。這種型別多型性允許針對不同型別使用同一程式碼片段。我們可以使用模板來實現這一點。

示例

#include<iostream>
using namespace std;
template <class T>
T maximum(T a, T b) {
   if(a > b) {
      return a;
   } else {
      return b;
   }
}
int main() {
   cout << "Max of (156, 78): " << maximum(156, 78) << endl;
   cout << "Max of (A, X): " << maximum('A', 'X') << endl;
}

輸出

Max of (156, 78): 156
Max of (A, X): X

更新於: 20-Aug-2019

3K+ 瀏覽

開啟 事業 >

完成課程,獲取認證

開始
廣告