如何在 C++ 中將一個類轉換為另一個類型別?
在本教程中,我們將討論一個程式,以瞭解如何在 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP