Forced type conversion in C ++
Example 1 define a member function in a class
Convert conver class objects to int type
# Include <iostream>
Using namespace STD;
Class conver
{
Public:
Int B;
Operator int () {return B;} // Note: The implementation of the function is written directly here.
};
Int main ()
{
Conver C;
C. B = 100;
// Printf ("% d", (INT) C );
Cout <(INT) C <Endl
Return 0;
}
Example 2 define a member function outside the class definition
Convert conver class objects to int type
# Include <iostream>
Using namespace STD;
Class conver
{
Public:
Int B;
Operator int (); // Note: Only the forced conversion function is declared here.
};
// Note: the forced conversion function is defined below
Cover: Operator int ()
{
Return B;
}
Int main ()
{
Conver C;
C. B = 100;
// Printf ("% d", (INT) C );
Cout <(INT) C <Endl;
Return 0;
}
The above two examples are compiled and run in Dev C ++ through
100 output