c++ - 此代码是否访问 C++ 类中的关联数组?

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

我正在查看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++ 中,operator[] 可以由类重载。 文档 必须已实现重载或从已实现的重载派生。

语法大致为:

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

AssociatedType 可以是一个引用。该方法可以是const

关于c++ - 此代码是否访问 C++ 类中的关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32484907/

相关文章:

c++11 - x86-SSE指令是否具有自动发布获取指令?

c++ - 在 netbeans 7.2 mac os x 上激活 C++ 11

c++ - 继承类的 vector

PHP & MySQL - 限制一个数组

c++ - 调用 vector.push_back() 时避免复制构造函数/析构函数

java - 写数组作为参数Java

arrays - 如何在 golang 中使用 type.NewArray 初始化数组?

c++11 参数包错误行为与 Apple LLVM 7.0.0 但适用于 GCC-5.1

c++ - 如何检测全局鼠标按键事件

C++ 析构函数泄漏动态内存