c++ - const and overloading operator -


i have generic map object. want overload operator[] map[key] return key's value. made 2 versions of subscript operator.

non-const:

valuetype& operator[](keytype key){ 

const:

const valuetype& operator[]( keytype&   key) const{ 

the non-const versions works fine when create const map have problem. write in main:

     const intmap map5(17);      map5[8]; 

and these errors:

ambiguous overload 'operator[]' (operand types 'const intmap {aka const mtm::mtmmap<int, int>}' , 'int')     invalid initialization of non-const reference of type 'int&' rvalue of type 'int'    

the error message ambiguity reflects compiler considering both of operator[]() possible candidates match map5[8]. both candidates equally (or bad, depending on how @ it).

the non-const version invalid because map5 const.

the const version requires initialising non-const reference keytype rvalue (the literal 8) invalid. error messages, keytype int.

either remove & keytype argument of const version, or make argument const.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -