3

I'm getting this error when I try to insert an element into an unordered_set:

error: invalid operands to binary expression ('const Play' and 'const Play')
        {return __x == __y;}

Here's a screenshot of the whole error: https://www.dropbox.com/s/nxq5skjm5mvzav3/Screenshot%202013-11-21%2020.11.24.png

This is my hash function:

struct Hash {

        size_t operator() (Play &play) {

            unsigned long hash = 5381;
            int c;

            string s_str = play.get_defense_name() + play.get_offense_name() + play.get_description();
            const char * str = s_str.c_str();

            while ( (c = *str++) )
                hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

            cout << hash << endl;
            return hash;

       }
    };

This is where I declare the unordered_list:

unordered_set<Play, Hash> Plays;

And this is my overloaded == for my Play class:

friend bool operator== (Play& p1, Play& p2)
    {
        return 
            (p1.get_defense_name() == p2.get_defense_name()) && 
            (p1.get_offense_name() == p2.get_offense_name()) &&
            (p1.get_description() == p2.get_description()); 
    }

Any idea what could be going on here?

Thanks.

4

2 回答 2

5

错误是说它试图比较const Playconst Play但你只operator ==提供Play

friend bool operator== (const Play& p1, const Play& p2)
    {
        return 
            (p1.get_defense_name() == p2.get_defense_name()) && 
            (p1.get_offense_name() == p2.get_offense_name()) &&
            (p1.get_description() == p2.get_description()); 
    }
于 2013-11-22T01:17:45.583 回答
2

看起来无序集正在寻找比较常量Play对象,但您==提供比较非常量对象。由于不允许删除 const-ness,编译器会产生错误。添加 const-ness 应该可以解决问题:

friend bool operator== (const Play& p1, const Play& p2)

const您还应该添加operator()

size_t operator() (const Play &play)
于 2013-11-22T01:18:02.023 回答