、设计一个三维空间中的向量类,要求用友元函数计算向量的和与差以及向量的长度。主函数
时间: 2024-06-06 18:08:04 浏览: 74
C++ 实验五 友元与静态成员
#include <iostream>
#include <cmath>
using namespace std;
class Vector3D{
private:
double x, y, z;
public:
Vector3D(double x=0, double y=0, double z=0): x(x), y(y), z(z){}
friend Vector3D operator+(Vector3D v1, Vector3D v2);
friend Vector3D operator-(Vector3D v1, Vector3D v2);
double length();
};
Vector3D operator+(Vector3D v1, Vector3D v2){
return Vector3D(v1.x+v2.x, v1.y+v2.y, v1.z+v2.z);
}
Vector3D operator-(Vector3D v1, Vector3D v2){
return Vector3D(v1.x-v2.x, v1.y-v2.y, v1.z-v2.z);
}
double Vector3D::length(){
return sqrt(x*x+y*y+z*z);
}
int main(){
Vector3D v1(1, 2, 3), v2(4, 5, 6);
Vector3D v3 = v1+v2;
Vector3D v4 = v1-v2;
double len = v1.length();
cout<<"v1+v2=("<<v3.x<<","<<v3.y<<","<<v3.z<<")"<<endl;
cout<<"v1-v2=("<<v4.x<<","<<v4.y<<","<<v4.z<<")"<<endl;
cout<<"v1的长度为:"<<len<<endl;
return 0;
}
阅读全文