Operator Overloading in a 3D Vector Class in C++


C++
#include<iostream>
using namespace std;
class vector
{
    float x;
    float y;
    float z; //data members
    public:
    vector(){ } //default constructor
    vector(float x,float y,float z) //parameterized constructor
    {
        this->x = x;
        this->y = y;
        this->z = z;
    }
    void display(); //member functions declaration
    void operator-(); //- operator overloading declaration
    void operator++(); //++ operator overloading declaration
    void operator--(); //-- operator overloading declaration
};
void vector::display() //member function definition
{
    cout<<"Vector : "<<x<<"i + "<<y<<"j + "<<z<<"k"<<endl;
}
void vector::operator-() //- operator overloading definition
{
    x = -x;
    y = -y;
    z = -z;
}
void vector::operator++() //++ operator overloading definition
{
    ++x;
    ++y;
    ++z;
}
void vector::operator--() //-- operator overloading definition
{
    --x;
    --y;
    --z;
}
int main()
{
    float a,b,c;
    cout<<"Enter three values : ";
    cin>>a>>b>>c;
    vector v1(a,b,c); //object created and parameterized constructor invoked
    v1.display(); //member function calling
    cout<<"-v1 : "<<endl;
    -v1; //operator- function calling
    v1.display();
    cout<<"++v1 : "<<endl;
    ++v1; //operator++ function calling
    v1.display();
    cout<<"--v1 : "<<endl;
    --v1; //operator-- function calling
    v1.display();
    return 0;
}
Enter three values : 3 4 -5
Vector : 3i + 4j + -5k
-v1 : 
Vector : -3i + -4j + 5k
++v1 : 
Vector : -2i + -3j + 6k
--v1 : 
Vector : -3i + -4j + 5k

Learn More...

Next Post Previous Post
No Comment
Add Comment
comment url