2012-02-29 139 views
2

我試圖用一個簡單的結構,地圖鍵:重載<運算符類內部

class Foo{ 
. 
. 
. 
    struct index{ 
    int x; 
    int y; 
    int z; 
    }; 

    bool operator<(const index a, const index b); 
    . 
    . 
    . 
} 

而且功能itslef:

bool Foo::operator<(const index a, const index b){ 
    bool out = True; 
    if (a.x == b.x){ 
    if (a.y == b.y){ 
     if (a.z >= b.z) out = false; 
    } 
    else if(a.y > b.y) out = false; 
    } else if (a.x > b.x) out = false; 
    return out; 
} 

然而,當我編譯錯誤:

memMC.h:35: error: 'bool Foo::operator<(Foo::index, Foo::index)' must take exactly one argument

據我瞭解這一點,編譯器要比較index這個Foo。那我該如何超載操作員呢?

回答

3

如果要比較兩個指標,將超載的index結構內:

struct index{ 
    int x; 
    int y; 
    int z; 
    bool operator<(const index& a) const; 
}; 

如果要比較一個Fooindex(我懷疑這一點,但我只是把這個在這裏以防萬一),刪除第二個參數,因爲它是沒有必要的:

class Foo{ 
    //... 
    bool operator<(const index& a) const; 
}; 

請注意,您應該通過引用傳遞的參數index,防止unnecesarry複製。

編輯:正如Als正確指出的那樣,這個操作符應該是const

+0

謝謝!這個問題在過去的幾個小時裏一直困擾着我。我沒有想到修復會如此簡單。 – Dennis 2012-05-04 22:36:33

2

<是二進制中綴比較運算符,即它需要兩個參數來進行比較,因此理想情況下它應該作爲一個自由函數來實現,但是如果將它作爲成員函數實現,那麼它將只使用一個參數。

它應將作爲參數傳遞給參數的參數與調用成員函數的對象進行比較。

你的成員相比,運營商應該是這樣的:

class Foo 
{ 
    //... 
    bool operator<(const index& rhs) const 
    { 
     /* comparison with *this */ 
    } 
    //... 
};