關系運算符重載


C++語言支持各種關系運算符重載(<,>,>=,<=,==),他們可用於比較C++內置的數據類型。

支持重載任意一個關系運算符,重載后的關系運算符可以用於比較類的對象。

/***
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;
}

運行結果:

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

D2 is less than D1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM