If the first program that C++ coders write is “Hello World”, then a definition of a 3D vector class is probably the second.
Let’s have a go:
#include <iostream> // For console output functionality
using namespace std; // Avoids having to use std:: scoping prefix
class Vector
{
public:
double x,y,z; // Representation
Vector(double a,double b,double c):x(a),y(b),z(c) { } // Constructor
friend ostream& operator<<(ostream& os,const Vector& v) // Non-member, thus must be friend, but defined inline
{ return os<<'('<<v.x<<','<<v.y<<','<<v.z<<')'; } // Output, e.g. (1,2,3)
};
int main() // The program
{ Vector v(1,2,3); // A test vector
cout << "v="<<v<<"\n"; // Output it
}
When this is run it produces the following output:
v=(1,2,3)
There’s not much we can do with this vector. We can read and write to the individual elements (x,y,z), but addition is labourious, e.g.
Vector u(-1,-3,-5);
cout<<"u="<<u<<"\n";
Vector s=Vector(u.x+v.x,u.y+v.y,u.z+v.z); // Sum of two vectors
cout<<"u+v="<<s<<"\n";
When this is run it adds the following output:
u=(-1,-3,-5)
u+v=(0,-1,-2)
Comments
There are currently no comments on this article.
Comment