C++ Programming

C++ Functions to Add, Subtract, Multiply and Divide Using Operator Overloading

Write a class to store x, y and z coordinates of a point in three dimensional space. Using operator overloading write functions to add, subtract, multiply and divide the vectors.

Source Code

#include<iostream>

#include<conio.h>

using namespace std;

class point

{

    int x,y,z;

    public:

    void getdata()

    {

        cout<<"Enter x: ";

        cin>>x;

        cout<<"Enter y: ";

        cin>>y;

        cout<<"Enter z: ";

        cin>>z;

    }

void showdata()

    {

        cout<<"("<<x<<","<<y<<","<<z<<")";

    }

point operator +(point p2)

    {

        point p;

        p.x=x+p2.x;

        p.y=y+p2.y;

        p.z=z+p2.z;

        return p;

    }

point operator -(point p2)

    {

        point p;

        p.x=x-p2.x;

        p.y=y-p2.y;

        p.z=z-p2.z;

        return p;

    }

point operator *(point p2)

    {

        point p;

        p.x=x*p2.x;

        p.y=y*p2.y;

        p.z=z*p2.z;

        return p;

    }

point operator /(point p2)

    {

        point p;

        p.x=x/p2.x;

        p.y=y/p2.y;

        p.z=z/p2.z;

        return p;

    }

};

int main()

{

    point p1,p2,p3;

    p1.getdata();

    p2.getdata();

    p1.showdata();

    p2.showdata();

    p3=p1+p2;

    p3.showdata();

    p3=p1-p2;

    p3.showdata();

    p3=p1*p2;

    p3.showdata();

    p3=p1/p2;

    p3.showdata();

    getch();

}

Output

operator overloading

Back to top button