此代码是否在 C++ 中访问 class 中的关联数组?
Is this code accessing an associative array in a class in C++?
我正在查看 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 是一个 class,它有被调用的方法,但同时他可以使用 document["hello"][=18= 访问它] 作为关联数组?这就是这里发生的事情吗?
在 C++ 中,operator[]
可以被 class 重载。 Document
必须已经实现了重载或派生自已经实现的重载。
语法大致是:
class Foo {
public:
AssociatedType operator [] (IndexingType i) {
//...
}
};
AssociatedType
可以作为参考。该方法可能是 const
.
运算符重载自 C++ 早期就可用。
在RapidJSON中,GenericValue
定义了几个重载的operator[]
,如:
template<typename Encoding, typename Allocator>
template<typename T >
GenericValue& rapidjson::GenericValue< Encoding, Allocator >::operator[](T* name)
而GenericDocument
是从GenericValue
推导出来的。
我正在查看 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 是一个 class,它有被调用的方法,但同时他可以使用 document["hello"][=18= 访问它] 作为关联数组?这就是这里发生的事情吗?
在 C++ 中,operator[]
可以被 class 重载。 Document
必须已经实现了重载或派生自已经实现的重载。
语法大致是:
class Foo {
public:
AssociatedType operator [] (IndexingType i) {
//...
}
};
AssociatedType
可以作为参考。该方法可能是 const
.
运算符重载自 C++ 早期就可用。
在RapidJSON中,GenericValue
定义了几个重载的operator[]
,如:
template<typename Encoding, typename Allocator>
template<typename T >
GenericValue& rapidjson::GenericValue< Encoding, Allocator >::operator[](T* name)
而GenericDocument
是从GenericValue
推导出来的。