Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ประเภทของ Polymorphism - Ad-hoc, Inclusion, Parametric และ Coercion


ที่นี่เราจะดูประเภทต่างๆ ของ Polymorphism (พหุรูป) ซึ่งมีดังนี้

  • Ad-Hoc
  • Inclusion
  • Parametric
  • Coercion

Polymorphism แบบ Ad-Hoc เรียกว่าการโอเวอร์โหลด (Overloading) ซึ่งอนุญาตให้ฟังก์ชันที่มีชื่อเดียวกันทำงานต่างกันสำหรับประเภทข้อมูลที่ต่างกัน ฟังก์ชันและออเปอเรเตอร์ทั้งคู่สามารถโอเวอร์โหลดได้ บางภาษาไม่รองรับการโอเวอร์โหลดออเปอเรเตอร์ แต่อันของฟังก์ชันเป็นเรื่องปกติ

ตัวอย่าง

#include <iostream>
using namespace std;
int add(int a, int b) {
    return a + b;
}
string add(string a, string b) {
    return a + b; // ต่อสตริง
}
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

Polymorphism แบบ Inclusion เรียกว่าการสับทายปิ้ง (Subtyping) ซึ่งอนุญาตให้ชี้ไปยังคลาสลูกโดยใช้พอยน์เตอร์หรืออ้างอิงของคลาสแม่ นี่คือ Polymorphism แบบ Runtime เราไม่รู้ประเภทของอ็อบเจกต์จริงจนกว่าจะรัน เราต้องใช้ฟังก์ชันเสมือน (virtual function) ใน C++ เพื่อให้ได้ Inclusion Polymorphism นี้

ตัวอย่าง

#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; // อ็อบเจกต์ของคลาสแม่
    ob1->print();
    ob1 = &derived_obj; // พอยน์เตอร์เดียวกันชี้ไปยังอ็อบเจกต์ลูก
    ob1->print();
}

ผลลัพธ์

This is base class.
This is derived class.

Polymorphism แบบ Coercion เรียกว่าการแปลงชนิด (Casting) ประเภทนี้เกิดขึ้นเมื่ออ็อบเจกต์หรือค่า primitive ถูกแปลงเป็นอีกชนิดหนึ่ง มีการแปลง 2 แบบ การแปลงโดยอัตโนมัติ (Implicit casting) ทำโดยคอมไพเลอร์ และการแปลงโดยแสดง (Explicit cast) ใช้ 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

Polymorphism แบบ Parametric เรียกว่าการผูกติดล่วงหน้า (Early Binding) ประเภทนี้อนุญาตให้ใช้โค้ดชิ้นเดียวกันสำหรับประเภทข้อมูลต่างๆ เราสามารถทำได้โดยใช้เทมเพลต (Templates)

ตัวอย่าง

#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