2015-09-09 26 views
2

我正在查看rapidjson可能整合的代码。我可以看到,由于新的C++ 11,你可以在C++中实现关联数组,但我不确定速度优势。然而,在他们的示例代码中,我看到的是:此代码访问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 = %s\n", document["hello"].GetString()); 

它看起来像文件是有方法被称为一类,但同时他能够使用文档[“你好”]访问它作为一个关联数组?这是怎么回事?

+0

我在这里没有看到任何矛盾。这只是一个句法的东西。如果在一种语言中,集合是对象(就像在C++中那样),为什么你不能同时使用下标语法和方法调用来使用它们呢? –

+0

C++在标准库('std :: map'和'std :: unordered_map')中有关联数组,所以这应该不会令人惊讶...... – rlbond

+0

http://stackoverflow.com/questions/4294100/creating-一个级索引器-操作者允许字符串参数串的索引 –

回答

3

在C++中,operator[]可以被类重载。 Document必须已经实现了一个过载或从一个已经实现的过载。

语法大致是:

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

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

0

运算符重载自C++早期开始就可用。

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

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

GenericDocument和从GenericValue的。