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

3

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

代码编译成功,但当我尝试使用它时:
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"];
                   ^

我可以理解数组下标可以是int或char,但是std::map如何处理char* /字符串呢?

1
list 的类型是什么? - NathanOliver
确切地说,列表是指向类的指针。 - Nick
@Nick,你正在尝试对指针进行下标访问,而不是调用你的运算符重载。 - molbdnilo
2个回答

6

如果你的list也是一个指针,那么你不能像之前那样使用[]操作符。因为list["3 city"]等价于list.operator[]("3 city")。如果你提供了一个指针,你需要使用list->operator[]("3 city")或者更可读的方式(*list)["3 city"]。当然,你也可以将列表设置为引用并正常使用:

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

这就是为什么现在每个人都使用&而不是*的原因。 - Nick
因为在C++中,*通常是不好看的和丑陋的;) - PiotrSliwa
我已经有5-6年没有用C++了,现在发现C++就像是糟糕的Java。这更像是一个新问题,但人们会做 Book *b = new Book(); 还是 Book &rb = *new Book(); 如果我选择第二个选项,那么我必须 delete &rb; 吗? - Nick
@Nick 实际上,你的例子是正确的,但我迄今为止还没有看到过这样的形式(我不认为这样做有意义)。现在有C++14可用,如果必须使用指针,则使用智能指针,例如auto b = std::make_unique();,您不再需要关心delete:) 如果您需要从指针获取引用,只需对其进行解引用Book& b = *bookPointer; - PiotrSliwa
我知道智能指针,昨天我刚将项目从C++升级到了C++11 :) 暂时还会保留手动删除,但会将指针改为引用。 - Nick

3

看起来list是一个指向IList对象的指针。因此,您应该尝试:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接