#include#ifndef VEC3D #define VEC3D class Vec3d { private: float vec[3]; public: Vec3d(); Vec3d(float x, float y, float z); Vec3d(const float vec[3]); Vec3d(const Vec3d& vec); float getX()const; float getY()const; float getZ()const; void setX(float x); void setY(float y); void setZ(float z); const Vec3d& operator=(const Vec3d& vec); float getLength()const; float getSquaredLength()const; Vec3d getUnit()const; Vec3d operator+(const Vec3d& vec)const; Vec3d operator-(const Vec3d& vec)const; Vec3d operator*(float x)const; Vec3d operator/(float x)const; float operator[](unsigned int i)const; float& operator[](unsigned int i); std::string toString()const; // friends friend Vec3d operator*(float x, const Vec3d& vec); }; Vec3d operator*(float x, const Vec3d& vec); #endif
#include "vec3d.hpp" #include#include using namespace std; Vec3d::Vec3d() { vec[0] = vec[1] = vec[2] = 0; } Vec3d::Vec3d(float x, float y, float z) { vec[0] = x; vec[1] = y; vec[2] = z; } Vec3d::Vec3d(const float vec[3]) { this->vec[0] = vec[0]; this->vec[1] = vec[1]; this->vec[2] = vec[2]; } Vec3d::Vec3d(const Vec3d& vec) { this->vec[0] = vec.vec[0]; this->vec[1] = vec.vec[1]; this->vec[2] = vec.vec[2]; } float Vec3d::getX()const { return vec[0]; } float Vec3d::getY()const { return vec[1]; } float Vec3d::getZ()const { return vec[2]; } void Vec3d::setX(float x) { vec[0] = x; } void Vec3d::setY(float y) { vec[1] = y; } void Vec3d::setZ(float z) { vec[2] = z; } const Vec3d& Vec3d::operator=(const Vec3d& vec) { this->vec[0] = vec.vec[0]; this->vec[1] = vec.vec[1]; this->vec[2] = vec.vec[2]; return *this; } float Vec3d::getSquaredLength()const { return ( vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2] ); } float Vec3d::getLength()const { return sqrt ( vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2] ); } Vec3d Vec3d::getUnit()const { Vec3d res(*this); float length = getLength(); res.vec[0] /= length; res.vec[1] /= length; res.vec[2] /= length; return res; } Vec3d Vec3d::operator+(const Vec3d& vec)const { Vec3d res(*this); res.vec[0] += vec[0]; res.vec[1] += vec[1]; res.vec[2] += vec[2]; return res; } Vec3d Vec3d::operator-(const Vec3d& vec)const { Vec3d res(*this); res.vec[0] -= vec[0]; res.vec[1] -= vec[1]; res.vec[2] -= vec[2]; return res; } Vec3d Vec3d::operator*(float x)const { Vec3d res(*this); res.vec[0] *= x; res.vec[1] *= x; res.vec[2] *= x; return res; } Vec3d Vec3d::operator/(float x)const { Vec3d res(*this); res.vec[0] /= x; res.vec[1] /= x; res.vec[2] /= x; return res; } float Vec3d::operator[](unsigned int i)const { return vec[i]; } float& Vec3d::operator[](unsigned int i) { return vec[i]; } string Vec3d::toString()const { stringstream ss; ss << "(" << vec[0] << "," << vec[1] << "," << vec[2] << ")"; return ss.str(); } Vec3d operator*(float x, const Vec3d& vec) { Vec3d res(vec); res.vec[0] *= x; res.vec[1] *= x; res.vec[2] *= x; return res; }
No hay comentarios:
Publicar un comentario