Tuesday, 26 July 2016

C++ overload operators

Three cases are enlisted below as templates -- . More could be added later...

(1) Box1 + Box2

// Overload + operator to add two Box objects.
Box operator+(const Box& b) 
{ 
    Box box;      // this is the new box to return
    box.length = this->length + b.length; 
    box.breadth = this->breadth + b.breadth; 
    box.height = this->height + b.height; 
    return box; 
}

(2) Box1 <  Box2 // Overload < operator to add two Box objects.
        bool operator<(Box &b)
        {
            if(this->l < b.l)
                {return true;}
            else if(this->b < b.b && this->l == b.l)
                {return true;}
            else if(this->h < b.h && this->b == b.b && this->l == b.l)
                {return true;}
            else
                {return false;}
        }



(3) Overloading the I/O operators

i) the output <<
//Overload operator << as specified
        friend ostream& operator<< (ostream &out, const Box &b)
        {
            cout<<b.l<<" "<<b.b<<" "<<b.h;
            return out;
        }


The above examples should be included as the public functions in the Class Box.

ref:

No comments:

Post a Comment