C++:运算符重载

c++ : operator overloading

本文关键字:重载 运算符 C++      更新时间:2023-10-16

我设计了与std::pair非常相似的简单结构。

struct pii{
    int first;          
    int second;         
    pii (int _first=-1, int _second=-1)
            : first(_first), second(_second)    {}
    //
    pii& operator=(const pii &ref){
        first=ref.first;
        second=ref.second;
        return *this;
    }
    pii operator+(const pii &ref){
        return pii(first+ref.first, second+ref.second);
    }
    //
    bool operator<(pii &ref){
        if(first<ref.first && second<ref.second)
            return true;
        return false;
    }
    bool operator>(pii &ref){
        return ref>(*this);
    }
    bool operator<=(pii &ref){
        return !((*this)>ref);
    }
    bool operator>=(pii &ref){
        return !((*this)<ref);
    }
    //
    bool operator==(pii &ref){
        if(first==ref.first && second==ref.second)
            return true;
        return false;
    }
    bool operator!=(pii &ref){
        return !((*this)==ref);
    }
};

假设有两个pii对象。我想使用比较操作(<><=>===!=(转换以下句子。

pii one, another;
//   I want to convert the below sentence.
if(one.first<=another.first && one.second<=another.second)

if(one<=another)//这不是正确的答案。

可以转换吗?那么,答案是什么?

这应该是比较第一个和第二个变量的正确代码:

bool operator<(pii &ref){
    return first<ref.first && second<ref.second;
}
bool operator>(pii &ref){
    return first>ref.first && second>ref.second;
}
bool operator<=(pii &ref){
    return first<=ref.first && second<=ref.second;
}
bool operator>=(pii &ref){
    return first>=ref.first && second>=ref.second;
}