Is Schrödinger's Cat
Object-Oriented? - Appendix A
Writing C++ Code I: The class TVector3D.
In this Appendix, we provide a C++ declaration and implementation of
the class TVector3D, illustrating the important C++ feature of
operator overloading. To take full advantage of the Appendices, some basic
background in C and C++ is required (either an introductory course in C++,
or some exposure to basic C++ through any of Refs 4 or other C++ textbook).
The header Vector3D.h declares the class TVector3D
class TVector3D
{
public:
TVector3D ();
TVector3D (double x, double y, double z);
~TVector3D ();
/* Operator Overloading */
TVector3D operator= (const TVector3D theVector);
TVector3D operator+= (const TVector3D theVector);
TVector3D operator-= (const TVector3D theVector);
TVector3D operator*= (const double theScalar);
private:
double x, y, z; //components of the vector
};
The implementation of the class TVector3D follows
#include <Vector3D.h>
TVector3D::TVector3D()
{
x = 0;
y = 0;
z = 0;
}
TVector3D::TVector3D(double a, double b, double c)
{
x = a;
y = b;
z = c;
}
TVector3D::~TVector3D()
{ // nothing to do
};
TVector3D TVector3D::operator= (const TVector3D theVector3D)
{
x = theVector3D.x;
y = theVector3D.y;
z = theVector3D.z;
return *this;
}
TVector3D TVector3D::operator+= (const TVector3D theVector3D)
{
x += theVector3D.x;
y += theVector3D.y;
z += theVector3D.z;
return *this;
}
TVector3D TVector3D::operator-= (const TVector3D theVector3D)
{
x -= theVector3D.x;
y -= theVector3D.y;
z -= theVector3D.z;
return *this;
}
TVector3D TVector3D::operator*= (const double theScalar)
{
x *= theScalar;
y *= theScalar;
z *= theScalar;
return *this;
}
In this design, the default constructor returns a null vector. Alternatively,
one might provide an implementation using a random number generator so
the constructor would instantiate a random TVector3D object. The
operators =, +=, ... are messages sent to an object of the TVector3D
class. Since the name of this object is not known, in the C/C++ language
it is denoted *this.
|