简体   繁体   English

operator []重载以接受char *作为下标

[英]operator[] overload to accept char * for subscript

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 ? 我可以理解数组下标是int或char,但那么std :: map是如何进行char * / strings的?

If your list is a pointer as well you can't use [] operator in the way you did. 如果您的list也是指针,则不能以您的方式使用[]运算符。 That's because list["3 city"] is equivalent to list.operator[]("3 city") . 这是因为list["3 city"]相当于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"] . 如果你提供指针,你必须使用list->operator[]("3 city")或 - 更可读 - (*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. 似乎list是指向IList对象的指针。 So you should try: p = (*list)["3 city"]; 所以你应该尝试:p =(* list)[“3 city”];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM