运算符重载"+""-""*"“<<”">>"
一、问题描述。
设计一个描述三维坐标的向量类vector3D,成员如下:数据成员:三个坐标x,y,z,float类型,私有访问属性公有函数成员:三个参数均有默认值的构造函数,默认值为0,0,0;重载输入输出运算符,输出格式为(x, y, z);重载加法+、减法-、数乘*(乘数在前,乘数为float类型)这三个运算符;在主函数中定义两个vector3D类对象v1,v2,均不带参数,之后输入数字1或2选择为v1输入赋值,还是为v1和v2输入赋值,对v1和v2进行加、减运算,对v1进行数乘运算,乘数由用户输入,最后输出三种运算结果。
二、程序流程图。
三、源代码。
#include<iostream>
#include <cmath>
#include <string>
using namespace std;
class vector3D{
private:
float x;
float y;
float z;
public:
vector3D(float xx = 0, float y = 0,float z=0);
friend istream& operator>>(istream& input, vector3D& v);
friend ostream& operator<<(ostream& output, vector3D& v);
vector3D operator+(vector3D B);
vector3D operator-(vector3D B);
float operator*(vector3D B);
};
vector3D::vector3D(float xx, float yy, float zz) :x(xx), y(yy), z(zz)
{
if (x == 0 && y == 0 && z == 0) cout << "已构造默认坐标" << endl;
else cout << "已构造坐标为" << x << "," << y << "," << z << "的坐标" << endl;
}
istream& operator>>(istream& input, vector3D& v)
{
input >> v.x >> v.y >> v.z;
return input;
}
ostream& operator<<(ostream& output, vector3D& v)
{
output << "(" << v.x << "," << v.y << "," << v.z << ")" << endl;
return output;
}
vector3D vector3D:: operator+(vector3D B)
{
return vector3D(x + B.x, y + B.y, z + B.z);
}
vector3D vector3D:: operator-(vector3D B)
{
return vector3D(x - B.x, y - B.y, z - B.z);
}
float vector3D:: operator*(vector3D B)
{
return x*B.x + y*B.y + z*B.z;
}
int main()
{
vector3D a, b;
cin >> a >> b;
cout << "a+b=" << a + b << endl;
cout << "a-b=" << a - b << endl;
cout << "a*b=" << a*b << endl;
}
四、代码实现。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了