Why do I need a conversion operator?
We know that for built-in types of data we can convert data by forcing the use of a translator, such as (int) 2.1f; a custom class is also a type, so objects in a custom class also need to support this operation in many cases, and C + + provides a conversion operator overloaded function. It makes it possible to strongly convert a custom class object.
Conversion operators are more specific in their life style, as follows:
Operator class name ();
The overloaded function of a conversion operator has no return type, and it is the same as the constructor of the class, which does not follow the rule that the function has a return type, and they do not return a value.
Let me look at an example to see how it works:
Example 1
//Program Author: Junning
//site: www.cndev-lab.com
//All manuscripts have copyright, if you want to reprint, please be sure to famous source and author
#include <iostream>
using namespace Std;
Class Test
{
Public:
Test (int a = 0)
{
cout<<this<< ":" <& lt; " Load Constructor! " <<a<<endl;
Test::a = A;
}
Test (test &temp)
{
cout<< "load copy constructor!" <<endl;
Test::a = Temp.a;
}
~test ()
{
cout<<this<< ":" << "Load destructor!" <<this->a<<endl;
Cin.get ();
}
Operator int ()//conversion operator
{
cout<<this<< ": <<" Load conversion operator Function! " <<this->a<<endl;
return test::a;
}
Public:
int A;
};
Int main ()
{
Test b;
cout<< "B's memory address" <<&b<<endl;
cout<< (int) b<<endl;//Strong conversion
System("pause");
}
In the example, we use the conversion operator to convert the object of the test class to the int type and output, pay attention to the operation State of the conversion operator function, and find that the temporary object is not produced, proving that it is not the same as the normal function, although it has a return statement.