Wednesday, October 1, 2014

Write a class to store x, y and z coordinates of a point in three dimensional spaces. Using operator overloading write friend function to add and subtract the vectors.

Code:


#include
#include
class friends
{
            int x,y,z;
            public:
            friends ()
            {
                        x=y=z=0;
            }
            void display()
            {
                        cout<<"("<
            }
            void get()
            {
                        cout<<"\nEnter coordinates(X,Y,Z):";
                        cin>>x>>y>>z;
            }
            friend friends operator+(friends,friends);
            friend friends operator-(friends,friends);
};
friends operator +(friends f1,friends f2)
{
            friends k;
            k.x=f1.x+f2.x;
            k.y=f1.y+f2.y;
            k.z=f1.z+f2.z;
            return k;
}
friends operator -(friends f1,friends f2)
{
            friends l;
            l.x=f1.x-f2.x;
            l.y=f1.y-f2.y;
            l.z=f1.z-f2.z;
            return l;
}
int main()
{
            clrscr();
            friends f1,f2,f3,f4;
            f1.get();
            f2.get();
            f3=f1+f2;
            cout<<"\nUsing + operator:";
            f3.display();
            cout<<"\nUsing - operator:";
            f4=f1-f2;
            f4.display();
            getch();
            return 0;
}

No comments:

Post a Comment