给我一个完整的包含一个简单的向量类vector的代码
时间: 2023-08-03 09:06:55 浏览: 47
好的,以下是一个简单的向量类 `Vector` 的代码示例:
```c++
#include <iostream>
#include <cmath>
class Vector {
public:
Vector(double x, double y, double z) : x_(x), y_(y), z_(z) {}
// 向量加法
Vector operator+(const Vector& other) const {
return Vector(x_ + other.x_, y_ + other.y_, z_ + other.z_);
}
// 向量减法
Vector operator-(const Vector& other) const {
return Vector(x_ - other.x_, y_ - other.y_, z_ - other.z_);
}
// 向量点乘
double operator*(const Vector& other) const {
return x_ * other.x_ + y_ * other.y_ + z_ * other.z_;
}
// 向量叉乘
Vector operator%(const Vector& other) const {
return Vector(y_ * other.z_ - z_ * other.y_,
z_ * other.x_ - x_ * other.z_,
x_ * other.y_ - y_ * other.x_);
}
// 向量数量乘
Vector operator*(double k) const {
return Vector(k * x_, k * y_, k * z_);
}
// 向量数量除
Vector operator/(double k) const {
return Vector(x_ / k, y_ / k, z_ / k);
}
// 向量模长
double Length() const {
return std::sqrt(x_ * x_ + y_ * y_ + z_ * z_);
}
// 归一化向量
Vector Normalize() const {
double len = Length();
if (len == 0) return Vector(0, 0, 0);
return (*this) / len;
}
void Print() const {
std::cout << "Vector(" << x_ << ", " << y_ << ", " << z_ << ")" << std::endl;
}
private:
double x_, y_, z_;
};
int main() {
Vector v1(1, 2, 3);
Vector v2(4, 5, 6);
Vector v3 = v1 + v2;
v3.Print(); // Vector(5, 7, 9)
Vector v4 = v1 - v2;
v4.Print(); // Vector(-3, -3, -3)
double dot = v1 * v2;
std::cout << "Dot product: " << dot << std::endl; // Dot product: 32
Vector v5 = v1 % v2;
v5.Print(); // Vector(-3, 6, -3)
Vector v6 = v1 * 2;
v6.Print(); // Vector(2, 4, 6)
Vector v7 = v1 / 2;
v7.Print(); // Vector(0.5, 1, 1.5)
double len = v1.Length();
std::cout << "Length: " << len << std::endl; // Length: 3.74166
Vector v8 = v1.Normalize();
v8.Print(); // Vector(0.267261, 0.534522, 0.801784)
return 0;
}
```
在这个代码示例中,我们定义了一个 `Vector` 类,包含了向量的加减、点乘、叉乘、数量乘、数量除、模长、归一化等基本操作。在 `main` 函数中,我们对这些操作进行了简单的测试。