设计一个MyVector类,表示向量。MyVector类包括
时间: 2024-05-12 08:20:21 浏览: 119
以下成员:
1. 私有变量:
- `double* data`:动态分配的数组,存储向量的每个分量的值;
- `int size`:向量的维数。
2. 构造函数:
- `MyVector(int size, double value = 0.0)`:构造一个维数为`size`,每个分量的值都为`value`的向量。
3. 拷贝构造函数:
- `MyVector(const MyVector& v)`:构造一个与向量`v`相同的新向量。
4. 析构函数:
- `~MyVector()`:释放动态分配的数组空间。
5. 成员函数:
- `int getSize() const`:返回向量的维数。
- `double get(int i) const`:返回向量第`i`个分量的值。
- `void set(int i, double value)`:设置向量第`i`个分量的值为`value`。
- `double norm() const`:返回向量的模长。
- `void normalize()`:将向量归一化。
- `MyVector add(const MyVector& v) const`:返回当前向量与向量`v`的和。
- `double dot(const MyVector& v) const`:返回当前向量与向量`v`的点积。
- `MyVector cross(const MyVector& v) const`:返回当前向量与向量`v`的叉积。
示例代码:
```cpp
#include <iostream>
#include <cmath>
class MyVector {
private:
double* data;
int size;
public:
MyVector(int size, double value = 0.0) {
this->size = size;
data = new double[size];
for (int i = 0; i < size; i++) {
data[i] = value;
}
}
MyVector(const MyVector& v) {
size = v.size;
data = new double[size];
for (int i = 0; i < size; i++) {
data[i] = v.data[i];
}
}
~MyVector() {
delete[] data;
}
int getSize() const {
return size;
}
double get(int i) const {
return data[i];
}
void set(int i, double value) {
data[i] = value;
}
double norm() const {
double sum = 0.0;
for (int i = 0; i < size; i++) {
sum += data[i] * data[i];
}
return std::sqrt(sum);
}
void normalize() {
double n = norm();
if (n != 0.0) {
for (int i = 0; i < size; i++) {
data[i] /= n;
}
}
}
MyVector add(const MyVector& v) const {
MyVector w(size);
for (int i = 0; i < size; i++) {
w.data[i] = data[i] + v.data[i];
}
return w;
}
double dot(const MyVector& v) const {
double sum = 0.0;
for (int i = 0; i < size; i++) {
sum += data[i] * v.data[i];
}
return sum;
}
MyVector cross(const MyVector& v) const {
if (size != 3 || v.size != 3) {
std::cerr << "Error: cross product is defined only for 3-dimensional vectors.\n";
exit(1);
}
MyVector w(size);
w.data[0] = data[1] * v.data[2] - data[2] * v.data[1];
w.data[1] = data[2] * v.data[0] - data[0] * v.data[2];
w.data[2] = data[0] * v.data[1] - data[1] * v.data[0];
return w;
}
};
int main() {
MyVector v(3, 1.0);
std::cout << "v = [" << v.get(0) << ", " << v.get(1) << ", " << v.get(2) << "]\n";
std::cout << "v.norm() = " << v.norm() << "\n";
v.normalize();
std::cout << "v.normalize() = [" << v.get(0) << ", " << v.get(1) << ", " << v.get(2) << "]\n";
MyVector u(3, 2.0);
std::cout << "u = [" << u.get(0) << ", " << u.get(1) << ", " << u.get(2) << "]\n";
std::cout << "u.norm() = " << u.norm() << "\n";
u.normalize();
std::cout << "u.normalize() = [" << u.get(0) << ", " << u.get(1) << ", " << u.get(2) << "]\n";
MyVector w = v.add(u);
std::cout << "w = v + u = [" << w.get(0) << ", " << w.get(1) << ", " << w.get(2) << "]\n";
double dot = v.dot(u);
std::cout << "v.dot(u) = " << dot << "\n";
MyVector cross = v.cross(u);
std::cout << "v.cross(u) = [" << cross.get(0) << ", " << cross.get(1) << ", " << cross.get(2) << "]\n";
return 0;
}
```
阅读全文