ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อทำความเข้าใจวิธีแปลงคลาสเป็นคลาสอื่นใน C/C++
การแปลงคลาสสามารถทำได้โดยใช้โอเปอเรเตอร์โอเวอร์โหลด ซึ่งช่วยให้สามารถกำหนดข้อมูลของประเภทคลาสหนึ่งให้กับวัตถุของคลาสประเภทอื่นได้
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
//type to which it will be converted
class Class_type_one {
string a = "TutorialsPoint";
public:
string get_string(){
return (a);
}
void display(){
cout << a << endl;
}
};
//class to be converted
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