ในส่วนนี้เราจะเรียนรู้เกี่ยวกับ Constructor แปลงชนิด (Conversion Constructor) ในคลาส C++ Constructor เป็นฟังก์ชันพิเศษของคลาส มีคุณสมบัติเฉพาะ เช่น ชื่อเหมือนชื่อคลาส ไม่คืนค่า ใช้สร้างอ็อบเจกต์ของคลาส บางครั้ง Constructor รับอาร์กิวเมนต์ บางครั้งไม่รับ
เมื่อ Constructor รับอาร์กิวเมนต์เพียงตัวเดียว จะกลายเป็น Conversion Constructor ซึ่งอนุญาตให้เกิดการแปลงชนิดอัตโนมัติไปยังคลาสที่กำลังสร้าง
ตัวอย่าง
#include <iostream>
using namespace std;
class my_class {
private:
int my_var;
public:
my_class(int x) { this->my_var = x; } // parameterized constructor
void display() { cout << "The value of my_var is: " << my_var << endl; }
};
int main() {
my_class my_obj(10);
my_obj.display();
my_obj = 50; // เรียก Conversion Constructor ที่นี่
my_obj.display();
}ผลลัพธ์
The value of my_var is: 10 The value of my_var is: 50