簡體   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