为了方便向量的相关运算,需要设计一个向量类。
类的设计如下:
#pragma once
#include <math.h>
#include "P3.h"
class CVector3
{
public:
CVector3(void);
virtual ~CVector3(void);
CVector3(double x, double y, double z);//绝对向量
CVector3(CP3 p);
CVector3(CP3 p0, CP3 p1);//相对向量
double Magnitude(void);//计算向量的模
CVector3 Normalize(void);//规范化向量
friend CVector3 operator + (CVector3 v0, CVector3 v1);//运算符重载
friend CVector3 operator - (CVector3 v0, CVector3 v1);
friend CVector3 operator * (CVector3 v, double scalar);
friend CVector3 operator * (double scalar, CVector3 v);
friend CVector3 operator / (CVector3 v, double scalar);
friend double DotProduct(CVector3 v0, CVector3 v1);//计算向量的点积
friend CVector3 CrossProduct(CVector3 v0, CVector3 v1);//计算向量的叉积
public:
float x;
float y;
float z;
};
具体实现如下:
#include "pch.h"
#include "Vector3.h"
CVector3::CVector3(void)
{
x = 0.0, y = 0.0, z = 1.0;//指向z轴正向
}
CVector3::~CVector3(void)
{
}
CVector3::CVector3(double x, double y, double z)//绝对向量
{
this->x = x;
this->y = y;
this->z = z;
}
CVector3::CVector3(CP3 p)
{
x = p.x;
y = p.y;
z = p.z;
}
CVector3::CVector3(CP3 p0, CP3 p1)//相对向量
{
x = p1.x - p0.x;
y = p1.y - p0.y;
z = p1.z - p0.z;
}
double CVector3::Magnitude(void)//向量的模
{
return sqrt(x * x + y * y + z * z);
}
CVector3 CVector3::Normalize(void)//规范化为单位向量
{
CVector3 vector;
double magnitude = sqrt(x * x + y * y + z * z);
if (fabs(magnitude) < 1e-4)
magnitude = 1.0;
vector.x = x / magnitude;
vector.y = y / magnitude;
vector.z = z / magnitude;
return vector;
}
CVector3 operator + (CVector3 v0, CVector3 v1)//向量的和
{
CVector3 vector;
vector.x = v0.x + v1.x;
vector.y = v0.y + v1.y;
vector.z = v0.z + v1.z;
return vector;
}
CVector3 operator - (CVector3 v0, CVector3 v1)//向量的差
{
CVector3 vector;
vector.x = v0.x - v1.x;
vector.y = v0.y - v1.y;
vector.z = v0.z - v1.z;
return vector;
}
CVector3 operator * (CVector3 v, double scalar)//向量与常量的积
{
CVector3 vector;
vector.x = v.x * scalar;
vector.y = v.y * scalar;
vector.z = v.z * scalar;
return vector;
}
CVector3 operator * (double scalar, CVector3 v)//常量与向量的积
{
CVector3 vector;
vector.x = v.x * scalar;
vector.y = v.y * scalar;
vector.z = v.z * scalar;
return vector;
}
CVector3 operator / (CVector3 v, double scalar)//向量数除
{
if (fabs(scalar) < 1e-4)
scalar = 1.0;
CVector3 vector;
vector.x = v.x / scalar;
vector.y = v.y / scalar;
vector.z = v.z / scalar;
return vector;
}
double DotProduct(CVector3 v0, CVector3 v1)//向量的点积
{
return(v0.x * v1.x + v0.y * v1.y + v0.z * v1.z);
}
CVector3 CrossProduct(CVector3 v0, CVector3 v1)//向量的叉积
{
CVector3 vector;
vector.x = v0.y * v1.z - v0.z * v1.y;
vector.y = v0.z * v1.x - v0.x * v1.z;
vector.z = v0.x * v1.y - v0.y * v1.x;
return vector;
}