Relations Operator Overloading

C ++ language support operator overloading relationships (<,>,> =, <=, ==), they can be used to compare the C ++ built-in data types.

A support overloading any relational operators, the relationship between the operator overloading may be used to compare an object class.

/***
overrealate.cpp
***/
#include<iostream>
using namespace std;

class Distance
{
    private:
        int feet;
        int inches;
    public:
        Distance()
        {
            feet = 0;
            inches = 0;
        }
        Distance(int f,int i)
        {
            feet = f;
            inches = i;
        }

        void displayDistance()
        {
            cout << "F: " << feet << " I: " << inches << endl; 
        }

        Distance operator- ()
        {
            feet = -feet;
            inches = -inches;
            return Distance(feet,inches);
        }
        bool operator <(const Distance& d)
        {
            if(feet < d.feet)
            {   
                return true;
            }
            if(feet == d.feet && inches < d.inches)
            {
                return true;
            }
            return false;
        }
};

int main()
{
    Distance D1(11,10), D2(5,11);

    if(D1 < D2)
    {
        cout << "D1 is less than D2 " << endl;
    }
    else
    {
        cout << "D2 is less than D1" << endl; 
    }
    return 0;
}

operation result:

exbot @ ubuntu: ~ / wangqinghe / C ++ / 20190808 $ ./overrelation

D2 is less than D1

Guess you like

Origin www.cnblogs.com/wanghao-boke/p/11319747.html