CPP-operator==,

如果已經定義了operator==,那麼operator!=很容易實現,只要調用operator==,然後取反。

bool Array::operator!=(const Array& v) const
{
    return !((*this) == v);
}

這個函數的形式實際上和具體的類無關。即如果定義了operator==,那麼總能根據這個模式定義operatot!=. 同樣,如果定義了<, 則很容易能夠定義>. 如果定義了==,則結合<和==,則能夠定義<=和>=. 標準文件util包含了一系列預先定義的這些關係操作符的模式。使用時只需定義operator==, operator<,則自動有operator!=, operator>, operator<=.因此從不需要定義多餘兩個比較操作符。看以下例子:爲array定義<.

bool operator< (const Array& v) const;

實現:

bool Array::operator< (const Array& v) const
{
    int n; //the length of the shortest of this object and v
    if(num <v.num)
    n = num;
    else
    n = v.num;
    for(int i=0;i<n;i++)
    if(p[i] <v.p[i])
    return true;
    else if(p[i]>v.p[i])
    return false;
    return num <v.num; //equal length
}

爲了自動使用別的比較操作符。需要在類定義文件中包含以下信息:

#include〈utility>
using namespace std::rel_ops;

單操作符:operator-

Array operator- () const;

Array Array::operator- () const
{
Array temp(*this); //creat a copy of this array object
for(int i=0;i

class Myclass{
public:
    bool operator== (const Myclass &vb) const {
            if(this->vx == vb.vx && this->vy == vb.vy && this->vz == vb.vz) return true;
            else return false;};
private:
    double  vx,vy,vz;
}

其實當在一個成員函數內部寫一個成員名字時候(如vx),編譯器將解釋爲this->vx。因此以上語句其實不需要明確指出this->vx;故代碼可以簡化:

class Myclass{
public:
    bool operator== (const Myclass &vb) const {
        return(vx == vb.vx && vy == vb.vy && vz == vb.vz) };
private:
    double  vx,vy,vz;
}

接下來實現矢量大小比較(長度)

bool operator<  (const Vector3d &vb) const {return (this->lengthsquare() < vb.lengthsquare());};

inline double lengthsquare() {return(vx*vx + vy*vy + vz*vz);};

這幾句總是給錯誤提示:
“the object has type qualifiers that are not compatible with the member function”,

因爲operator< 聲明爲一個常函數,而函數lengthsquare()沒有聲明爲常函數。

bool operator<  (const Vector3d &vb) const {return (this->lengthsquare() < vb.lengthsquare());};

inline double lengthsquare() const{return(vx*vx + vy*vy + vz*vz);};

其他comparison operator:

bool operator== (const Vector3d &vb) const {return(vx == vb.vx && vy == vb.vy && vz == vb.vz);}
        bool operator!= (const Vector3d &vb) const {return !(*this == vb);};
        bool operator<  (const Vector3d &vb) const {return (this->lengthsquare() < vb.lengthsquare());};
        bool operator>= (const Vector3d &vb) const {return !(*this < vb);};
        bool operator>  (const Vector3d &vb) const {return (*this >= vb) && (*this != vb);};
        bool operator<= (const Vector3d &vb) const {return !(*this > vb);};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章