Saturday, April 17, 2021

simple program using operator overloading (OOP) (70)

 #include<iostream>

using namespace std;

class Distance  //here i make a class name Distance 

{

private:

int feet,inches;  

public:

   Distance () //here i define the default constructor 

    {

    feet=0;

    inches=0;

}

Distance (int a,int b) //here i define a parameterized constructor

{

feet=a;

inches=b;

}

void display() //here i define a function that display the values

{

cout<<"feet="<<feet<<"inches="<<inches<<endl;

}

     Distance  operator *(Distance  o3); //here i overload the + operator

     Distance  operator /(Distance  o4); //here i overload the - operator

     friend bool operator==(Distance  &d1, Distance  &d2); //here i overload the == operator

     friend bool operator!=(Distance  &d1, Distance  &d2);//here i overload the != operator

     friend bool operator>=(Distance  &d1, Distance  &d2); //here i overload the >= operator

     friend bool operator<=(Distance  &d1, Distance  &d2);//here i overload the <= operator

};

Distance Distance::operator *( Distance o3) //here i overload the * operator

{

Distance result;

result.feet=feet*o3.feet;

result.inches=inches*o3.inches;

return result;

}

Distance Distance::operator /(Distance o4) //here i overload the / operator

{

Distance result;

result.feet=feet/o4.feet;

result.inches=inches/o4.inches;

return result;

}

bool operator==(Distance&d1, Distance &d2)//here i overload the == operator

  return (d1.feet==d2.feet||d1.inches==d2.inches);

}

bool operator!=(Distance&d1, Distance &d2)//here i overload the != operator

  return (d1.feet!=d2.feet||d1.inches!=d2.inches);

}

bool operator>=(Distance&d1, Distance &d2)//here i overload the >= operator

  return (d1.feet>=d2.feet||d1.inches>=d2.inches);

}

bool operator<=(Distance&d1, Distance &d2)//here i overload the <= operator

  return (d1.feet<=d2.feet||d1.inches<=d2.inches);

}

int main()

{

Distance d1,d2,d3;

cout<<"\t\twhen calling first object"<<endl;

d1=Distance(6,7);

d1.display();

cout<<endl;

cout<<"\t\twhen calling second object"<<endl;

d2=Distance (3,4);

d2.display();

cout<<endl;

d3=d1*d2;

cout<<"\t\tafter multiply the two  object:"<<endl;

d3.display();

cout<<endl;

d3=d1/d2;

cout<<"\t\tafter divide the two  object:"<<endl;

d3.display();

cout<<endl;

cout<<endl;

cout<<"\tafter checking the equality between two distance:"<<endl;

if(d1 == d2)

    {

        cout << "Both the  are equal";

    }   

    cout<<endl;

    cout<<"\tafter checking the unequality between two distance:"<<endl;

if(d1 != d2)

    {

        cout << "Both the are not equal";

    } 

    cout<<endl;

cout<<"\tafter checking this >=:"<<endl;

if(d1 >= d2)

    {

        cout<<"d1 is greater then and equal to d2"<<endl;

    }   

    cout<<endl;

    cout<<"\tafter checking this <=:"<<endl;

if(d1 <= d2)

    {

        cout <<"d2 less then and equal to d1";

    } 

}

No comments:

Post a Comment