繁体   English   中英

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

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

我有以下代码:

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);
}

代码编译好,但是当我尝试使用它时:

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

我有:

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

我可以理解数组下标是int或char,但那么std :: map是如何进行char * / strings的?

如果您的list也是指针,则不能以您的方式使用[]运算符。 这是因为list["3 city"]相当于list.operator[]("3 city") 如果你提供指针,你必须使用list->operator[]("3 city")或 - 更可读 - (*list)["3 city"] 当然,您也可以将列表作为参考并正常使用:

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

似乎list是指向IList对象的指针。 所以你应该尝试:p =(* list)[“3 city”];

暂无
暂无

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

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