C++ 上下文错误

C++ context error

我有一个使用 rapidjson JSON 解析器的 C++ class Tester.cpp。

这里是代码的简化版本:

using namespace std;
using namespace rapidjson;

int main(int argc, char** argv)
{
   ...
 //Parse the JSON
          rapidjson::Document document;
          document.Parse(buffer);
              add_rules_to_tester(document);
   ...
    }

void add_rules_to_tester(rapidjson::Document document)
{...}

我的头文件 Tester.h 如下所示(再次缩写):

using namespace std;
using namespace rapidjson;

void add_rules_to_tester(rapidjson::Document document);

当我注释掉 main 方法中的行 add_rules_to_tester 时,我没有收到任何错误。当我取消注释该行时,出现以下编译时错误。

In file included from Tester.h:38:0,
             from Tester.cpp:28:
rapidjson/document.h: In function ‘int main(int, char**)’:
rapidjson/document.h:2076:5: 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&);
 ^
Tester.cpp:163:34: error: within this context
add_rules_to_tester(document);
                              ^
In file included from Tester.cpp:28:0:
Tester.h:76:6: error:   initializing argument 1 of ‘void add_rules_to_tester(rapidjson::Document)’
 void add_rules_to_tester(rapidjson::Document document);

对可能出现的问题有什么建议吗?在我看来,我以某种方式误解了名称空间的使用,但如果我可以提供任何其他信息,请告诉我。谢谢!

rapidjson/document.h: In function ‘int main(int, char**)’:
rapidjson/document.h:2076:5: 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&);

编译器告诉您 GenericDocument 的复制构造函数被声明为私有的,因此您不能在 GenericDocument 之外使用它 class。

您在这条语句中调用复制构造函数,同时通过创建副本将其作为参数传递:

add_rules_to_tester(document);

解决方案:

通过引用传递 document 对象。

void add_rules_to_tester(rapidjson::Document& document) //Note & here
{...}

并将其命名为 add_rules_to_tester(document);

要补充以上答案, 确保头文件中的函数或 main 上方的函数声明也已更改! 我犯了一个错误,没有改变我的头文件,花了 2 个小时弄清楚:( 像下面这样更改函数声明!

void add_rules_to_tester(rapidjson::Document& document) //add &!!