c++中vector3
时间: 2023-11-17 21:03:44 浏览: 54
在C++中,Vector3通常是指三维向量,它可以用来表示三维空间中的位置、方向、速度等。通常情况下,我们可以使用结构体或类来实现Vector3。
以下是一个使用结构体实现Vector3的例子:
```c++
struct Vector3 {
float x, y, z;
Vector3(float x = 0, float y = 0, float z = 0) : x(x), y(y), z(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 s) const { return Vector3(x * s, y * s, z * s); }
Vector3 operator/(float s) const { return Vector3(x / s, y / s, z / s); }
float dot(const Vector3& v) const { return x * v.x + y * v.y + z * v.z; }
Vector3 cross(const Vector3& v) const { return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); }
float length() const { return sqrt(x * x + y * y + z * z); }
Vector3 normalize() const { return *this / length(); }
};
```
以上代码定义了一个Vector3结构体,包含了向量的x、y、z三个分量,以及一些常用的向量运算,例如加减乘除、点积、叉积、长度、归一化等。
以下是一个使用类实现Vector3的例子:
```c++
class Vector3 {
public:
float x, y, z;
Vector3(float x = 0, float y = 0, float z = 0) : x(x), y(y), z(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 s) const { return Vector3(x * s, y * s, z * s); }
Vector3 operator/(float s) const { return Vector3(x / s, y / s, z / s); }
float dot(const Vector3& v) const { return x * v.x + y * v.y + z * v.z; }
Vector3 cross(const Vector3& v) const { return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); }
float length() const { return sqrt(x * x + y * y + z * z); }
Vector3 normalize() const { return *this / length(); }
};
```
以上代码定义了一个Vector3类,与结构体实现的例子类似,不同之处在于使用了类的封装特性,将成员变量和成员函数分别定义在了public和private中。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)