2023.4.12编程一小时打卡
一、问题描述:
设计一个描述三维坐标的向量类vector3D,成员如下:
数据成员: 三个坐标x,y,z,float类型,私有访问属性
公有函数成员:三个参数均有默认值的构造函数,默认值为0,0,0;重载输入输出运算符,输出格式为(x, y, z);
重载加法+、减法-、数乘*(乘数在前,乘数为float类型)这三个运算符;
在主函数中定义两个vector3D类对象v1,v2,均不带参数,之后输入数字1或2选择为v1输入赋值,还是为v1和v2输入赋值,对v1和v2进行加、减运算,对v1进行数乘运算,乘数由用户输入,最后输出三种运算结果。
二、解题思路:
定义一个类,根据题目要求编写成员数据及成员函数,根据输入输出的格式编写主函数,最后编译运行。
三、代码实现:
1 #include<iostream> 2 3 #include<string> 4 5 using namespace std; 6 7 class vector3D 8 9 { 10 11 private: 12 13 float x,y,z; 14 15 public: 16 17 vector3D(float a=0,float b=0,float c=0):x(a),y(b),z(c){} 18 19 friend istream& operator>>(istream &,vector3D &); 20 21 friend ostream& operator<<(ostream &,vector3D &); 22 23 vector3D operator+(vector3D &a); 24 25 vector3D operator-(vector3D &a); 26 27 friend vector3D operator*(float s,vector3D &a); 28 29 }; 30 31 istream& operator>>(istream &put,vector3D &v) 32 33 { 34 35 put>>v.x>>v.y>>v.z; 36 37 return put; 38 39 } 40 41 ostream& operator<<(ostream &out,vector3D &v) 42 43 { 44 45 out<<"("<<v.x<<","<<v.y<<","<<v.z<<")"<<endl; 46 47 return out; 48 49 } 50 51 vector3D vector3D::operator+(vector3D &a) 52 53 { 54 55 return vector3D(x+a.x,y+a.y,z+a.z); 56 57 } 58 59 vector3D vector3D::operator-(vector3D &a) 60 61 { 62 63 return vector3D(x-a.x,y-a.y,z-a.z); 64 65 } 66 67 vector3D operator*(float s,vector3D &a) 68 69 { 70 71 return vector3D(s*a.x,s*a.y,s*a.z); 72 73 } 74 75 int main() 76 77 { 78 79 vector3D v1,v2; 80 81 int n; 82 83 float s; 84 85 cin>>n; 86 87 if(n==1) 88 89 { 90 91 cin>>v1>>s; 92 93 } 94 95 else if(n==2) 96 97 { 98 99 cin>>v1>>v2>>s; 100 101 } 102 103 cout<<v1+v2; 104 105 cout<<v1-v2; 106 107 cout<<s*v1; 108 109 return 0; 110 111 }

浙公网安备 33010602011771号