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

ตัวดำเนินการแปลงชนิดข้อมูล (Conversion Operators) ใน C++ ทำงานอย่างไร?

ในบทความนี้ เราจะมาเรียนรู้เกี่ยวกับตัวดำเนินการแปลงชนิดข้อมูล (Conversion Operators) ในภาษา C++ ซึ่งรองรับการออกแบบเชิงวัตถุ ทำให้เราสามารถสร้างคลาสสำหรับวัตถุในโลกจริงเป็นชนิดข้อมูลเฉพาะได้

บางครั้งเราต้องการแปลงวัตถุของชนิดข้อมูลเฉพาะไปเป็นชนิดข้อมูลอื่น หรือชนิดข้อมูลพื้นฐาน เพื่อทำการแปลงนี้ เราสามารถใช้ตัวดำเนินการแปลงชนิดข้อมูล ซึ่งถูกสร้างขึ้นในลักษณะคล้ายกับการโอเวอร์โหลดตัวดำเนินการภายในคลาส

ในตัวอย่างนี้ เราจะใช้คลาสสำหรับจำนวนเชิงซ้อน ที่มีสมาชิกสองตัวคือ ส่วนจริงและส่วนจินตภาพ เมื่อเรากำหนดค่าวัตถุของคลาสนี้ให้กับตัวแปรชนิด double จะเกิดการแปลงเป็นค่ามากนิธโดยอัตโนมัติผ่านตัวดำเนินการแปลงชนิดข้อมูล

โค้ดตัวอย่าง:

#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) {} // default constructor
    double mag() { // normal function to get magnitude
        return getMagnitude();
    }
    operator double() { // Conversion operator to get magnitude
        return getMagnitude();
    }
private:
    double getMagnitude() { // Find magnitude of complex object
        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;
}

ผลลัพธ์

Magnitude using normal function: 11.6619
Magnitude using conversion operator: 11.6619