How to I use the overloaded operator [] in the same class?

Viewed 60

Example

class MyMap {
    std::map<K,V> m_map;
    public:
        void myFunc( K const& a, V const& b ) {
    
        // want to use [] operator on the current object.

        // something like this->[a] = b;
        }
    
        V const& operator[]( K const& key ) const {
            //body
        }
    }

How do I access the MyMap with a given key in the function myFunc() using operator[] ?

2 Answers

You can dereference on this, e.g.

void myFunc( K const& a, V const& b ) {
    (*this)[a];
}

or call the operator[] in function-call syntax:

void myFunc( K const& a, V const& b ) {
    this->operator[](a);
}

BTW: The overloaded operator[] returns V const&, on which you can't perform assignment.

   // want to use [] operator on the current object.
  // something like this->[a] = b;

You can use the operator using the object (*this), so

(*this)[a] = b;

or you can explicitly call the method operator[],

this->operator[](a) = b;
(*this).operator[](a) = b; 

But, as pointed by songyuanyao, remember to add the non-const version of operator[],

    V & operator[] (K const & key)
     { return m_map[key]; }

if you want assign a new value to the returned reference.

Related