monkey
monkey

Reputation: 591

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

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[] ?

Upvotes: 3

Views: 64

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

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.

Upvotes: 4

max66
max66

Reputation: 66200

   // 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.

Upvotes: 2

Related Questions