匯東網


重載運算符聲明爲成員函數與否的兩種寫法

[編輯] [转简体]
|
作者:huidong | 分類:【編程】C/C++
[ 32 瀏覽 0 評論 5 贊 8 踩 ]

概要

正文

聲明爲非成員函數,並將運算符重載聲明爲類的友元,寫出來像這樣:

class id {  
public:  
    int type;  
    int st;  
    int sst;  
    int i;  
    int ii;  
  
    // 也可以寫在類的外面
    friend bool operator==(const id& lhs, const id& rhs)
    {  
        return (lhs.type == rhs.type   
                && lhs.st == rhs.st   
                && lhs.sst == rhs.sst   
                && lhs.i == rhs.i   
                && lhs.ii == rhs.ii);  
    }
};

優點:清晰明了地表示了比較的兩個對象類型,避免混淆。使用 friend 是因爲可能在比較時需要訪問類中的 private 和 protected 字段(雖然這裏沒用上)。

如果寫成成員函數,則像這樣:

class id {  
public:  
    int type;  
    int st;  
    int sst;  
    int i;  
    int ii;  
  
    bool operator==(const id& other) const {  
        return (this->type == other.type   
                && this->st == other.st   
                && this->sst == other.sst   
                && this->i == other.i   
                && this->ii == other.ii);  
    }  
};

這種寫法我見得更多。

[ 5] [ 8]


 評論區  0 條評論

+ 添加評論