Overload Access and C ++ Assignment

I am writing a hash table for my class structs struct, and I would like to add some syntactic sugar to my implementation.

template <typename HashedObj, typename Object>
Object & Dictionary<HashedObj, Object>::operator[](HashedObj & key)
{
  return items.lookup(key);
}

This works great when I do something like cout <Syrovatsky ["MyKey"]. But how can I do the assignment using parentheses? Sort of:

dict["mykey"] = "something";

And no, this is not part of my homework (not a pun), I just want to learn a little C ++.

+3
source share
3 answers

, . . (, , ). , []. (LHS), (RHS) ( <<, ). [] Object, Object, , [] .

, , [] . , ? , Object lookup ?

, . , , NULL . , Object ? , . [] LHS. ( [] std::map, BTW)

, lookup "" Object, . , - "", - "" , . , .

lookup , , , , [] LHS . , . , ...

, , , lookup?

P.S. , [] ( lookup) const HashedObj& HashedObj. , , (, ) . , ...

+5

2 . , const, data access, , , "".

+3

, , , std::map. std::map , . , , , .

So, if you have one std::map<K,V> mymap, then the call mymap[someKey]will either return a reference to the value associated with someKey, or create a new type object by Vcalling V()(the default constructor is V), and then return a link to this new object, which allows the caller to assign a value to the object.

+2
source

Source: https://habr.com/ru/post/1720975/


All Articles