ในบทความนี้ เราจะมาเรียนรู้เกี่ยวกับตัวดำเนินการแปลงชนิดข้อมูล (Conversion Operators) ในภาษา C++ ซึ่งรองรับการออกแบบเชิงวัตถุ (Object-Oriented Design) ทำให้เราสามารถสร้างคลาสสำหรับวัตถุในโลกจริงเป็นชนิดข้อมูลเฉพาะ (Concrete Types) ได้
บางครั้งเราต้องการแปลงวัตถุของชนิดข้อมูลเฉพาะไปเป็นชนิดข้อมูลอื่น หรือชนิดข้อมูลพื้นฐาน (Primitive Data Types) เพื่อทำการแปลงนี้ เราสามารถใช้ตัวดำเนินการแปลงชนิดข้อมูล ซึ่งถูกสร้างขึ้นในลักษณะคล้ายกับการโอเวอร์โหลดตัวดำเนินการ (Operator Overloading) ภายในคลาส
ในตัวอย่างนี้ เราจะใช้คลาสสำหรับจำนวนเชิงซ้อน (Complex Numbers) ที่มีสมาชิกสองตัวคือ ส่วนจริง (Real) และส่วนจินตภาพ (Imaginary) เมื่อเรากำหนดค่าวัตถุของคลาสนี้ให้กับตัวแปรชนิด double จะเกิดการแปลงเป็นค่ามากนิธ (Magnitude) โดยอัตโนมัติผ่านตัวดำเนินการแปลงชนิดข้อมูล
โค้ดตัวอย่าง
#include <iostream>
#include <cmath>
using namespace std;
class My_Complex {
private:
double real, imag;
public:
My_Complex(double re = 0.0, double img = 0.0) : real(re), imag(img) {} // Constructor เริ่มต้น
double mag() { // ฟังก์ชันทั่วไปสำหรับหาค่ามากนิธ
return getMagnitude();
}
operator double() { // ตัวดำเนินการแปลงเป็น double เพื่อคืนค่ามากนิธ
return getMagnitude();
}
private:
double getMagnitude() { // คำนวณค่ามากนิธของจำนวนเชิงซ้อน
return sqrt(real * real + imag * imag);
}
};
int main() {
My_Complex complex(10.0, 6.0);
cout << "Magnitude using normal function: " << complex.mag() << endl;
cout << "Magnitude using conversion operator: " << complex << endl;
return 0;
}ผลลัพธ์
Magnitude using normal function: 11.6619 Magnitude using conversion operator: 11.6619