Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 295
monkey Avatar asked Dec 12 '25 03:12

monkey


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

like image 121
songyuanyao Avatar answered Dec 14 '25 16:12

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!