ในบทช่วยสอนนี้ เราจะอภิบายโปรแกรมเพื่อทำความเข้าใจวิธีแปลงคลาสหนึ่งเป็นอีกคลาสหนึ่งใน C/C++
การแปลงคลาสสามารถทำได้ด้วยการโอเวอร์โหลดออเปอเรเตอร์ ซึ่งอนุญาตให้ข้อมูลของชนิดคลาสหนึ่งถูกกำหนดให้กับออบเจ็กต์ของอีกคลาสหนึ่ง
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
// คลาสปลายทางที่จะแปลงเป็น
class Class_type_one {
string a = "TutorialsPoint";
public:
string get_string() {
return (a);
}
void display() {
cout << a << endl;
}
};
// คลาสต้นทางที่จะแปลง
class Class_type_two {
string b;
public:
void operator=(Class_type_one a) {
b = a.get_string();
}
void display() {
cout << b << endl;
}
};
int main() {
// type one
Class_type_one a;
// type two
Class_type_two b;
// type conversion
b = a;
a.display();
b.display();
return 0;
}เอาต์พุต
TutorialsPoint TutorialsPoint