* xz:
But this does not always apply.
Sometimes you may want something like the following as in Java:
Coordinate{
//first constructor
public Coordinate(double x, double y, "Descartes"){
...
}
//second constructor
public Coordinate(double rho, double theta, "Polar") {
this(rho*Math.cos(theta), rho*Math.sin(theta),
"Descartes");
}
}
Try something like (disclaimer: off-the-cuff)
class Polar
{
private:
double myRho;
double myTheta;
public:
Polar(): myRho(0), myTheta(0) {}
Polar( double rho, double theta ): myRho( rho ), myTheta( theta ) {}
double rho() const { return myRho; } // Or more elaborate, reducing.
double theta() const { return myTheta; }
// More, like rotation, value operations.
// No modifiers.
};
class Cartesian
{
private:
double myX;
double myY;
public:
Cartesian(): myX(0), myY(0) {}
Cartesian( double x, double y ): myX( x ), myY( y ) {}
double x() const { return myX; }
double y() const { return myY; }
// More, like tranlation, value operations.
};
Cartesian cartesianFrom( Polar const& v ) { ... }
Polar polarFrom( Cartesian const& v ) { ... }
class AngleAsPoint: public Cartesian
{
public:
AngleAsPoint(): myPoint() {}
AngleAsPoint( double rho )
: myRho( rho ), myPoint( cartesianFrom( rho ) )
{}
double rho() const { return myRho; } // Or more elaborate, reducing.
double theta() const { return 1.0; }
Cartesian rotated( Cartesian other ) const
{
return Cartesian(
x()*other.x() - y*other.y(), x()*other.y() + y().other.x()
);
}
AngleAsPoint rotated( AngleAsPoint const& amount ) const
{
return rotated( static_cast<Cartesian const&>( amount ) );
}
// More, value operations.
// No modifiers.
};
class Coordinate: public Cartesian
{
public:
Coordinate(): Cartesian() {}
Coordinate( Polar const& value ): Cartesian( cartesianFrom( value ) ) {}
Coordinate( Cartesian const& value ): Cartesian( value ) {}
Polar asPolar() const { return polarFrom( *this ); }
operator Polar() const { return asPolar(); }
// Polar-specific operations, adapted.
Coordinate rotated( AngleAsPoint const& amount ) const
{
return amount.rotated( *this );
}
};
The above may suffer from premature optimization, because it assumes that
trigonometric operations will be Really Slow relative to basic arithmetic
operations. Which is not necessarily the case on modern computers. Also, I
just fetched some old math up from subconcious (only on my first cup of coffee
here), so you'd better check the math! ;-)
Cheers, & hth.,
- Alf