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

Constructor Overloading ใน C++


เหมือนกับ Function Overloading ที่เป็นคุณสมบัติหลักของภาษา Object-Oriented เราสามารถใช้ชื่อฟังก์ชันเดียวกันได้ถ้าชุดพารามิเตอร์ต่างกัน ที่นี่เราจะดูวิธี Overload Constructor ของ Class ใน C++ Constructor Overloading มีแนวคิดสำคัญดังนี้:

  • Constructor ที่ Overload ต้องมีชื่อเดียวกันและจำนวน Arguments ต่างกัน
  • Constructor ที่ถูกเรียก ขึ้นอยู่กับจำนวนและชนิดของ Arguments ที่ส่งเข้ามา
  • ต้องส่ง Argument ตอนสร้าง Object มิฉะนั้น Constructor จะไม่รู้ว่าจะเรียกตัวไหน

ตัวอย่าง

#include <iostream>
using namespace std;

class Rect {
private:
    int area;
public:
    Rect() {
        area = 0;
    }
    Rect(int a, int b) {
        area = a * b;
    }
    void display() {
        cout << "The area is: " << area << endl;
    }
};

main() {
    Rect r1;
    Rect r2(2, 6);
    r1.display();
    r2.display();
}

ผลลัพธ์

The area is: 0
The area is: 12