运算符重载"+""-""*"“<<”">>"

发布时间 2023-04-20 23:25:47作者: liuxuechao

一、问题描述。

设计一个描述三维坐标的向量类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;

}

四、代码实现。