设计一个三维向量类Vector。该类包含有三个float类型的数据成员x、y、z,用于表示向量的三维;该类还包含一些函数成员,具体如下: 1) Vector类包含两个构造函数。第一个为无参数构造函数,该函数能将向量的三个数据成员均初始化为0;第二个构造函数带有三个float型的数据成员(v1、v2、v3),其值分别用于初始化x、y、z; 2) Vector类包含有一个成员函数Print,用于显示该向量; 3) Vector类中重载运算符+和-,完成两个向量的相加和相减运算,以成员函数的方式重载; 4) Vector类中重载运算符+和-,完成向量与浮点数的相加和相减运算,以友元函数的方式重载; 5) Vector类中重载运算符*,完成向量的点乘运算,以友元函数的形式重载; 在main函数中编写测试代码,测试这几个成员函数,通过Print函数显示运算结果。
时间: 2024-04-13 15:29:36 浏览: 175
下面是一个实现上述要求的 Vector 类的示例代码:
```cpp
#include <iostream>
class Vector {
private:
float x;
float y;
float z;
public:
Vector() : x(0), y(0), z(0) {}
Vector(float v1, float v2, float v3) : x(v1), y(v2), z(v3) {}
void Print() const {
std::cout << "(" << x << ", " << y << ", " << z << ")" << std::endl;
}
Vector operator+(const Vector& other) const {
Vector result(x + other.x, y + other.y, z + other.z);
return result;
}
Vector operator-(const Vector& other) const {
Vector result(x - other.x, y - other.y, z - other.z);
return result;
}
friend Vector operator+(const Vector& vector, float scalar);
friend Vector operator+(float scalar, const Vector& vector);
friend Vector operator-(const Vector& vector, float scalar);
friend Vector operator-(float scalar, const Vector& vector);
friend float operator*(const Vector& vector1, const Vector& vector2);
};
Vector operator+(const Vector& vector, float scalar) {
Vector result(vector.x + scalar, vector.y + scalar, vector.z + scalar);
return result;
}
Vector operator+(float scalar, const Vector& vector) {
return vector + scalar;
}
Vector operator-(const Vector& vector, float scalar) {
return vector + (-scalar);
}
Vector operator-(float scalar, const Vector& vector) {
return (-vector) + scalar;
}
float operator*(const Vector& vector1, const Vector& vector2) {
float result = vector1.x * vector2.x + vector1.y * vector2.y + vector1.z * vector2.z;
return result;
}
int main() {
Vector v1(1.0f, 2.0f, 3.0f);
Vector v2(4.0f, 5.0f, 6.0f);
Vector sum = v1 + v2;
Vector difference = v1 - v2;
float dotProduct = v1 * v2;
Vector scalarSum = v1 + 2.0f;
Vector scalarDifference = 3.0f - v2;
std::cout << "v1: ";
v1.Print();
std::cout << "v2: ";
v2.Print();
std::cout << "v1 + v2: ";
sum.Print();
std::cout << "v1 - v2: ";
difference.Print();
std::cout << "v1 * v2: " << dotProduct << std::endl;
std::cout << "v1 + 2.0: ";
scalarSum.Print();
std::cout << "3.0 - v2: ";
scalarDifference.Print();
return 0;
}
```
这个代码实现了 Vector 类,包含了构造函数、打印函数、向量相加、相减、点乘运算符的重载。你可以在主程序中测试这些成员函数,并通过 Print 函数显示运算结果。
阅读全文