I have 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);
}
code compiles ok, 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 understand that array subscript is int or char, but then how std::map is doing char* / strings ?
If your list
is a pointer as well you can't use []
operator in the way you did. That's because list["3 city"]
is equivalent to list.operator[]("3 city")
. If you provide pointer, you'd have to use list->operator[]("3 city")
or - what is more readable - (*list)["3 city"]
. Of course, you can also make your list a reference and use normally:
auto& listRef = *list;
p = listRef["3 city"];
It seems list is a pointer to IList object. So you should try: p = (*list)["3 city"];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.