Implicit type conversion: Difference between revisions

Added C++ implementation
m (→‎{{header|Phix}}: added syntax colouring the hard way, phix/basics)
(Added C++ implementation)
Line 219:
<pre>
Name=Mike
</pre>
 
=={{header|C++}}==
C++ supports almost all of the same implicit conversions as the C example above. However it does not allow implicit conversions to enums and is more strict with some pointer conversions. C++ allows implicit conversions on user defined
types. The example below shows implicit conversions between polar and Cartesian points.
<lang cpp>#include <iostream>
#include <math.h>
 
struct PolarPoint;
 
// Define a point in Cartesian coordinates
struct CartesianPoint
{
double x;
double y;
// Declare an implicit conversion to a polar point
operator PolarPoint();
};
 
// Define a point in polar coordinates
struct PolarPoint
{
double rho;
double theta;
// Declare an implicit conversion to a Cartesian point
operator CartesianPoint();
};
 
// Implement the Cartesian to polar conversion
CartesianPoint::operator PolarPoint()
{
return PolarPoint
{
sqrt(x*x + y*y),
atan2(y, x)
};
}
 
// Implement the polar to Cartesian conversion
PolarPoint::operator CartesianPoint()
{
return CartesianPoint
{
rho * cos(theta),
rho * sin(theta)
};
}
 
int main()
{
// Create a Cartesian point
CartesianPoint cp1{2,-2};
// Implicitly convert it to a polar point
PolarPoint pp1 = cp1;
// Implicitily convert it back to a Cartesian point
CartesianPoint cp2 = pp1;
std::cout << "rho=" << pp1.rho << ", theta=" << pp1.theta << "\n";
std::cout << "x=" << cp2.x << ", y=" << cp2.y << "\n";
}</lang>
{{out}}
<pre>
rho=2.82843, theta=-0.785398
x=2, y=-2
</pre>
 
125

edits