/*
C++向量类 -- Vector3
向量基本操作:
1.向量分量
2.向量运算(赋值、加减、点乘和叉乘)
3.向量比较
4.向量与标量的运算(乘除)
5.向量标准化
6.向量的距离
*/
class Vector3 {
//公共
public:
//分量
float x, y, z;
//构造函数
Vector3() {} //1.默认
Vector3(const Vector3 &v)
: x(v.x), y(v.y), z(v.z) {} //2.参数为向量
Vector3(float vx, float vy, float vz)
: x(vx), y(vy), z(vz) {} //3.参数为三个分量
/
// 基本运算符操作
// "=" 赋值运算符
Vector3 &operator = (const Vector3 &v) {
x = v.x;
y = v.y;
z = v.z;
return *this; //返回指针
}
// "==" 比较运算符
bool operator == (const Vector3 &v) const {
bool b = (x == v.x && y == v.y && z == v.z);
return b;
}
// "!=" 不等于运算符
bool operator != (const Vector3 &v) const {
bool b = (x != v.x && y != v.y && z != v.z);
return b;
}
//
// 向量基本运算
/
// 向量直接置零
void zero() {
x = y = z = 0.0f;
}
// 向量符号取反
Vector3 operator - () const {
return Vector3(-x, -y, -z);
}
// 向量相加
Vector3 operator + (const Vector3 &v) const {
return Vector3(
x + v.x,
y + v.y,
z + v.z
);
}
// 向量相减
Vector3 operator - (const Vector3 &v) const {
return Vector3(
x - v.x,
y - v.y,
z - v.z
);
}
// 向量与标量相乘
Vector3 operator * (float v) const {
return Vector3(x * v, y * v, z * v);
}
// 向量与标量相除
Vector3 operator / (float v) const {
// 判断v是否为0 如果为0返回原向量 否则返回相除后的向量
if (v == 0)
v = 1;
float _v = 1.0f / v;
return Vector3(x * _v, y * _v, z * _v);
}
// "+=" 运算
Vector3 &operator += (const Vector3 &v) {
x += v.x;
y += v.y;
z += v.z;
return *this;
}
// "-=" 运算
Vector3 &operator -= (const Vector3 &v) {
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
// "*=" 运算
Vector3 &operator *= (float v) {
x *= v;
y *= v;
z *= v;
return *this;
}
// "/=" 运算
Vector3 &operator /= (float v) {
// 判断v是否为0 如果为0返回原向量 否则返回相除后的向量
if (v == 0)
v = 1;
float _v = 1.0f / v;
x *= _v;
y *= _v;
z *= _v;
return *this;
}
// 标准化向量
void normalize() {
// 获取模的平方(分量的平方和)
float sumOfSquare = x * x + y * y + z * z;
// 如果模为0 即该向量为0向量 不作处理直接返回
if (sumOfSquare == 0.0f)
return;
// 开方取模
float length = sqrt(sumOfSquare);
// 取倒数
float inverse = 1.0f / sqrt(length);
x *= inverse;
y *= inverse;
z *= inverse;
}
// 向量点乘
float operator * (const Vector3 &v) const {
return x * v.x + y * v.y + z * v.z;
}
};
// 向量取模
inline float vector3Length(const Vector3 &v) {
float length = v.x * v.x + v.y * v.y + v.z * v.z;
return sqrt(length);
}
// 向量叉乘
inline Vector3 vector3Cross(const Vector3 &v1, const Vector3 &v2) {
return Vector3(
v1.y * v2.z - v1.z * v2.y,
v1.z * v2.x - v1.x * v2.z,
v1.x * v2.y - v1.y * v2.x
);
}
// 与标量相乘
inline Vector3 operator * (const Vector3 &v, float w) {
return Vector3(
w * v.x,
w * v.y,
w * v.z
);
}
// 向量之间的距离
inline float vector3Distance(const Vector3 &v1, const Vector3 &v2) {
float dx = v1.x - v2.x;
float dy = v1.y - v2.y;
float dz = v1.z - v2.z;
float sumOfSquare = dx * dx + dy * dy + dz * dz;
return sqrt(sumOfSquare);
}
C++向量操作类
猜你喜欢
转载自blog.csdn.net/zhunju0089/article/details/103444666
今日推荐
周排行