Thursday, March 29, 2012

vector class in c++

This is the header file for my vector class its the simplest form of a vector class in c++ and i save it as a vec3.h file

class vector3

{
/*
vector class and method defnition goes here
*/
public:

double x, y, z;

// Constructor
vector3() : x(0.0), y(0.0),z(0.0){};
vector3(double a_x,double a_y,double a_z) : x(a_x), y(a_y),z(a_z){};

// Methods
double magnitude();
double dotProduct(vector3 d_v);
vector3 crossProduct(vector3 c_v);
vector3 normalize();
vector3 add(vector3 a_v);
vector3 sub(vector3 s_v);
vector3 mult(vector3 m_v);
};

Below in the cpp file for the class

#include
#include "vec3.h"

/*
Vector class methods
*/
double vector3::magnitude()
{
return (double)sqrt((x * x) + (y * y) + (z * z));
}

double vector3::dotProduct(vector3 d_v)
{
return (x * d_v.x + y * d_v.y + z * d_v.z);
}

vector3 vector3::crossProduct(vector3 c_v)
{
return vector3((y * c_v.z) - (z * c_v.y), (z * c_v.x) - (x * c_v.z), (x * c_v.y) - (y * c_v.x));
}

vector3 vector3::normalize()
{
double mag = (1.0 / magnitude());
double i = x * mag;
double j = y * mag;
double k = z * mag;
return vector3(i,j,k);
}

vector3 vector3::add(vector3 a_v)
{
return vector3(x+a_v.x, y+a_v.y, z+a_v.z);
}

vector3 vector3::sub(vector3 s_v)
{
return vector3(x-s_v.x,y-s_v.y,z-s_v.z);
}

vector3 vector3::mult(vector3 m_v)
{
return vector3 (x*m_v.x,y*m_v.y,z*m_v.z);
}