Operator [] overload to accept char * for index

I have the following code:

class IList{
public:
    virtual const Pair *get(const char *key) const = 0;

    inline const Pair *operator[](const char *key) const;
};

inline const Pair *IROList::operator[](const char *key) const{
    return get(key);
}

      

the code compiles fine, but when I try to use it:

IList *list = (IList *) SomeFactory();
Pair *p;
p = list["3 city"];

      

I got:

test_list.cc:47:19: error: invalid types β€˜IList*[const char [7]]’ for array subscript
  p = list["3 city"];
                   ^

      

I can figure out if the index of the array is int or char, but then how does std :: map do char * / strings?

+3


source to share


2 answers


If yours is list

also a pointer, you cannot use the operator the []

way you did. This is because it is list["3 city"]

equivalent list.operator[]("3 city")

. If you specified a pointer, you would need to use list->operator[]("3 city")

or - which is more readable - (*list)["3 city"]

. Of course, you can also make your list a link and use normally:



auto& listRef = *list;
p = listRef["3 city"];

      

+6


source


The list seems to be a pointer to an IList object. So you should try: p = (* list) ["3 city"];



+3


source







All Articles