繁体   English   中英

使用std :: map时,重载运算符会产生错误

[英]Overloaded operator generates errors when using std::map

class A
{
private:
    int a;
public:
    A( int set )
    {
        a = set;
    };
    ~A();
    bool operator <(const A& ref )
    {
        return this->a < ref.a;
    };
    bool operator ==(const A& ref )
    {
        return this->a == ref.a;
    };
};

int _tmain(int argc, _TCHAR* argv[])
{

    map<A,int>m;
    A a( 1 );
    m.insert( make_pair( a, 2 ) );
    for( map<A,int>::iterator it = m.begin(); it != m.end(); ++it )
    {

    }
    return 0;
}

生成C2678: http : //msdn.microsoft.com/zh-cn/library/ys0bw32s( v=vs.80) .aspx

对于操作员<

如果我使用m.find还将为运算符生成==如何解决这个问题?

更具体地说,错误导致:

template<class _Ty>
    struct less
        : public binary_function<_Ty, _Ty, bool>
    {   // functor for operator<
    bool operator()(const _Ty& _Left, const _Ty& _Right) const
        {   // apply operator< to operands
        return (_Left < _Right);
        }
    };

在功能上

最终案例:

struct MASTERPLAYER
{
    int a;
    bool operator==( const MASTERPLAYER& ref ) const 
    {
        return a == ref.a;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{

    MASTERPLAYER m;
    vector<MASTERPLAYER>v;
    v.push_back( m );
    std::find( v.begin(), v.end(), 2 );

}

您想将函数标记为const ,以表示它们不修改调用它们的对象:

bool operator <(const A& ref ) const
{
    return a < ref.a;
};
bool operator ==(const A& ref ) const
{
    return a == ref.a;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM