【问题标题】:Is this code accessing an associative array in a class in C++?此代码是否访问 C++ 类中的关联数组?
【发布时间】:2015-12-05 17:43:54
【问题描述】:

我正在查看 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 = %s\n", document["hello"].GetString());

看起来 Document 是一个具有被调用方法的类,但同时他能够使用 document["hello"] 作为关联数组来访问它?这是怎么回事?

【问题讨论】:

  • 我在这里没有看到任何矛盾。这只是一个语法问题。如果在一种语言中,集合是对象(如在 C++ 中),为什么不能同时使用下标语法和方法调用来使用它们?
  • C++ 在标准库中有关联数组(std::mapstd::unordered_map),所以这不足为奇...

标签: c++ arrays c++11 associative-array rapidjson


【解决方案1】:

在 C++ 中,operator[] 可以被类重载。 Document 必须已经实现了重载或派生自已实现的重载。

语法大致是:

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

AssociatedType 可能是一个参考。方法可能是const

【讨论】:

    【解决方案2】:

    从 C++ 早期就可以使用运算符重载。

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

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

    GenericDocument 派生自GenericValue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 2021-10-05
      • 2013-05-04
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      相关资源
      最近更新 更多