我正在查看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/