简体   繁体   English

C++ - 将rapidjson::Document 作为参数传递给函数

[英]C++ - Passing rapidjson::Document as an argument to a function

I'm passing pointer to rapidjson::Document as an argument.我将指向rapidjson::Document指针作为参数传递。

foo(rapidjson::Document* jsonDocument)
{
    std::cout << jsonDocument["name"] << std::endl;
}

But I cannot do jsonDocument["name"] to access the name attribute.但是我不能用jsonDocument["name"]来访问 name 属性。

Attempting to not use pointers leads to an error:尝试不使用指针会导致错误:

error: 'rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>::GenericDocument(const rapidjson::GenericDocument<Encoding, Allocator, StackAllocator>&) [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>; StackAllocator = rapidjson::CrtAllocator]' is private
GenericDocument(const GenericDocument&);

Can someone help me?有人能帮我吗?

Use a reference or a value as argument.使用引用或值作为参数。 Using the [] with a pointer will try to use your document as if it was an array of document.使用带有指针的[]将尝试使用您的文档,就好像它是一个文档数组。 A reference or a value will call the expected operator.引用或值将调用预期的运算符。

// a const reference
foo(const rapidjson::Document& jsonDocument) {
    std::cout << jsonDocument["name"] << std::endl;
}

// a copy (or move)
foo(rapidjson::Document jsonDocument) {
    std::cout << jsonDocument["name"] << std::endl;
}

I'd recommend you to use the reference, as your function don't need to consume any resources in the document, but only observe and print a value.我建议您使用参考,因为您的函数不需要消耗文档中的任何资源,而只需观察和打印一个值。

The call of this function will look like this:此函数的调用将如下所示:

rapidjson::Document doc = /* ... */;

foo(doc);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM