2012-02-29 141 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 */ 
    } 
    //... 
};