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

Early Binding และ Late Binding ใน C++

ในส่วนนี้เราจะดูว่า Early Binding และ Late Binding ใน C++ คืออะไร Binding (การผูก) หมายถึงกระบวนการแปลง identifier (ตัวระบุ) ให้เป็น address (ที่อยู่) สำหรับตัวแปรและฟังก์ชันทุกตัว จะมีการ binding ทุกครั้ง สำหรับฟังก์ชัน คือการจับคู่การเรียกใช้กับ definition (นิยาม) ของฟังก์ชันที่ถูกต้องโดย compiler Binding ทำได้ทั้ง compile time และ runtime

Early Binding (Compile-time Polymorphism)

เป็น polymorphism แบบ compile time ที่ผูกที่อยู่กับการเรียกฟังก์ชันโดยตรง Function overloading เป็นตัวอย่างของ early binding

ตัวอย่าง

#include <iostream>
using namespace std;

class Base {
public:
    void display() {
        cout << "In Base class" << endl;
    }
};

class Derived: public Base {
public:
    void display() {
        cout << "In Derived class" << endl;
    }
};

int main(void) {
    Base *base_pointer = new Derived;
    base_pointer->display(); // เรียก Base::display() เพราะไม่มี virtual
    return 0;
}

ผลลัพธ์

In Base class

Late Binding (Run-time Polymorphism)

เป็น polymorphism แบบ runtime ใน binding แบบนี้ compiler จะเพิ่มโค้ดที่ระบุประเภทอ็อบเจ็กต์ขณะ runtime แล้วจับคู่การเรียกกับ definition ที่ถูกต้อง ทำได้โดยใช้ virtual function

ตัวอย่าง

#include <iostream>
using namespace std;

class Base {
public:
    virtual void display() {
        cout << "In Base class" << endl;
    }
};

class Derived: public Base {
public:
    void display() {
        cout << "In Derived class" << endl;
    }
};

int main() {
    Base *base_pointer = new Derived;
    base_pointer->display(); // เรียก Derived::display() เพราะมี virtual
    return 0;
}

ผลลัพธ์

In Derived class