定义三维向量类array,利用运算符重载实现array对象的加法(+)、减法(-)与内积(*)。 主函数中程序创建两个array类型的对象A1与A2,并输入六个数字,分别为A1、A2赋值,打印输出A1+A2,A1-A2,A1*A2的结果。
时间: 2024-05-06 10:17:34 浏览: 49
下面是对应的代码实现:
```c++
#include <iostream>
using namespace std;
class array {
public:
double x, y, z;
array() {}
array(double x, double y, double z) : x(x), y(y), z(z) {}
array operator+(const array &v) const {
return array(x + v.x, y + v.y, z + v.z);
}
array operator-(const array &v) const {
return array(x - v.x, y - v.y, z - v.z);
}
double operator*(const array &v) const {
return x * v.x + y * v.y + z * v.z;
}
};
int main() {
double x1, y1, z1, x2, y2, z2;
cout << "Please input six numbers:" << endl;
cin >> x1 >> y1 >> z1 >> x2 >> y2 >> z2;
array A1(x1, y1, z1), A2(x2, y2, z2);
cout << "A1 + A2 = (" << A1.x + A2.x << ", " << A1.y + A2.y << ", " << A1.z + A2.z << ")" << endl;
cout << "A1 - A2 = (" << A1.x - A2.x << ", " << A1.y - A2.y << ", " << A1.z - A2.z << ")" << endl;
cout << "A1 * A2 = " << A1 * A2 << endl;
return 0;
}
```
运行结果示例:
```
Please input six numbers:
1 2 3 4 5 6
A1 + A2 = (5, 7, 9)
A1 - A2 = (-3, -3, -3)
A1 * A2 = 32
```
阅读全文