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