编写程序定义向量类 Vector,重载运算符+、-、*和=,实现向量之间的加、减、乘、赋值运算;重载 运算符>>、<<实现向量的输入、输出功能。
时间: 2023-12-25 21:05:19 浏览: 138
以下是向量类 Vector 的定义及重载运算符的实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
class Vector {
public:
Vector() {}
Vector(const vector<double>& v) : vec(v) {}
Vector operator+(const Vector& rhs) const {
if (vec.size() != rhs.vec.size()) {
throw "Sizes don't match";
}
vector<double> res(vec.size());
for (int i = 0; i < vec.size(); ++i) {
res[i] = vec[i] + rhs.vec[i];
}
return Vector(res);
}
Vector operator-(const Vector& rhs) const {
if (vec.size() != rhs.vec.size()) {
throw "Sizes don't match";
}
vector<double> res(vec.size());
for (int i = 0; i < vec.size(); ++i) {
res[i] = vec[i] - rhs.vec[i];
}
return Vector(res);
}
Vector operator*(double k) const {
vector<double> res(vec.size());
for (int i = 0; i < vec.size(); ++i) {
res[i] = vec[i] * k;
}
return Vector(res);
}
Vector& operator=(const Vector& rhs) {
vec = rhs.vec;
return *this;
}
friend istream& operator>>(istream& is, Vector& v);
friend ostream& operator<<(ostream& os, const Vector& v);
private:
vector<double> vec;
};
istream& operator>>(istream& is, Vector& v) {
int n;
is >> n;
vector<double> tmp(n);
for (int i = 0; i < n; ++i) {
is >> tmp[i];
}
v = Vector(tmp);
return is;
}
ostream& operator<<(ostream& os, const Vector& v) {
os << "[ ";
for (int i = 0; i < v.vec.size(); ++i) {
os << v.vec[i] << " ";
}
os << "]";
return os;
}
int main() {
Vector v1, v2;
cout << "Enter the first vector: ";
cin >> v1;
cout << "Enter the second vector: ";
cin >> v2;
cout << "v1 = " << v1 << endl;
cout << "v2 = " << v2 << endl;
cout << "v1 + v2 = " << v1 + v2 << endl;
cout << "v1 - v2 = " << v1 - v2 << endl;
cout << "2 * v1 = " << 2 * v1 << endl;
cout << "v1 = v2 = " << (v1 = v2) << endl;
return 0;
}
```
在上面的程序中,向量类 Vector 中重载了运算符 +、-、* 和 =,并且定义了友元函数重载运算符 >> 和 <<。其中,运算符 + 和 - 分别实现了向量的加法和减法,需要先判断两个向量的维数是否相同;运算符 * 实现了向量与标量的乘法;运算符 = 实现了向量的赋值操作。友元函数重载运算符 >> 实现了向量的输入,需要先输入向量的维数,再输入向量中的每个元素;友元函数重载运算符 << 实现了向量的输出,将向量的每个元素用空格隔开并放在方括号内。在 main 函数中,先输入两个向量,然后分别进行加、减、乘、赋值操作,并输出结果。
阅读全文