先决条件:在C++,高级C++中进行类型转换|转换运算符
通过类转换,可以将属于特定类类型的数据分配给属于另一类类型的对象。
例子:
假设有两个类“ A”和“ B”。如果我们要将属于“ A”类的详细信息分配给“ B”类的对象,则可以通过以下方式实现–
B(object of class B) = A(object of class A)
where ‘=’ has been overloaded for objects of class type ‘B’.
类转换可以通过转换函数来实现,该转换函数是通过使用运算符重载来完成的。
例子:
#include
using namespace std;
// Destination class, i.e
// Class to which another class to be converted
class Class_type_one {
string a = "GeeksforGeeks";
public:
// Member function which returns
// string type data
string get_string()
{
return (a);
}
// Member function to display
void display()
{
cout << a << endl;
}
};
// Source class, i.e
// Class type which will be converted
// to the destination class type
class Class_type_two {
string b;
public:
// Operator overloading which accepts data
// of the Destination class and
// assigns those data to the source class
// Here it is for the conversion of
// Class_type_two to Class_type_one
void operator=(Class_type_one a)
{
b = a.get_string();
}
// Member function for displaying
// the data assigned to b.
void display()
{
cout << b << endl;
}
};
int main()
{
// Creating object of class Class_type_one
Class_type_one a;
// Creating object of class Class_type_two
Class_type_two b;
// CLass type conversion
// using operator overloading
b = a;
// Displaying data of object
// of class Class_type_one
a.display();
// Displaying data of object
// of class Class_type_two
b.display();
return 0;
}
输出:
GeeksforGeeks
GeeksforGeeks
想要从精选的最佳视频中学习和练习问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。