如何在 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

更新日期: 25-2-2020

5K+ 瀏覽

點亮你的職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.