这段代码是在c++中访问类中的关联数组吗?

Is this code accessing an associative array in a class in C++?

本文关键字:访问 数组 关联 c++ 段代码 代码      更新时间:2023-10-16

我正在查看rapidjson代码以进行可能的集成。我可以看到,由于新的c++ 11,您实际上可以在c++中执行关联数组,尽管我不确定速度优势。然而,在他们的示例代码中,我看到这样:

 Document document; // Default template parameter uses UTF8 and MemoryPoolAllocator.
    char buffer[sizeof(json)];
    memcpy(buffer, json, sizeof(json));
    if (document.ParseInsitu(buffer).HasParseError())
        return 1;
    printf("nAccess values in document:n");
    assert(document.IsObject());    // Document is a JSON value represents the root of DOM. Root can be either an object or array.
    assert(document.HasMember("hello"));
    assert(document["hello"].IsString());
    printf("hello = %sn", document["hello"].GetString());

它看起来像文档是一个类,有方法被调用,但同时他能够访问它使用文档["hello"]作为一个关联数组?这就是这里发生的事吗?

在c++中,operator[]可以被类重载。Document必须要么实现了重载,要么从重载派生而来。

语法大致如下:

class Foo {
public:
    AssociatedType operator [] (IndexingType i) {
        //...
    }
};

AssociatedType可能是参考。方法可以是const

操作符重载在c++早期就已经可用了。

在RapidJSON中,有几个重载operator[]GenericValue中定义,如:

template<typename Encoding, typename Allocator>
template<typename T >
GenericValue& rapidjson::GenericValue< Encoding, Allocator >::operator[](T* name)   

GenericDocument是由GenericValue衍生而来