C++ MongoDB 客户端作为 class 成员
C++ MongoDB Client as a class member
我正在编写服务器端 C++ 音乐应用程序。我坚持数据库部分,我选择 MongoDB 去,我不是 C++ 的老板。
我创建了一个存储 MongoDB 唯一实例的数据库 class,我想像这样即时创建多个 MongoDB 客户端
this->setDatabaseURI(&this->uri, "mongodb://localhost:27017");
mongocxx::client *cli1 = this->createNewClient();
mongocxx::client *cli2 = this->createNewClient();
mongocxx::client *cli3 = this->createNewClient();
auto db1 = cli1["myAppDB"];
auto db2 = cli2["myAppDB"];
auto db3 = cli3["myAppDB"];
编译器说:
PATH/Database.cpp:31:20: error: array subscript is not an integer
auto db1 = cli1["myAppDB"];
^~~~~~~~~~
PATH/Database.cpp:32:20: error: array subscript is not an integer
auto db2 = cli2["myAppDB"];
^~~~~~~~~~
PATH/Database.cpp:33:20: error: array subscript is not an integer
auto db3 = cli3["myAppDB"];
^~~~~~~~~~
3 errors generated.
目标是使用指针动态创建客户端,并在需要新客户端时调用 createNewClient() 函数。
mongocxx::client *Database::createNewClient()
{
mongocxx::client *cli = new mongocxx::client();
return (cli);
}
如果我喜欢它,它会起作用:
mongocxx::client conn;
auto db = conn["myAppDB"];
我不明白为什么?这种情况下的“[]”是什么?
您尝试在指针上调用[] 运算符,这显然不起作用。您应该取消引用指针并改为在对象实例上调用它:
auto d = (*cli1)["myAppDB"];
我正在编写服务器端 C++ 音乐应用程序。我坚持数据库部分,我选择 MongoDB 去,我不是 C++ 的老板。
我创建了一个存储 MongoDB 唯一实例的数据库 class,我想像这样即时创建多个 MongoDB 客户端
this->setDatabaseURI(&this->uri, "mongodb://localhost:27017");
mongocxx::client *cli1 = this->createNewClient();
mongocxx::client *cli2 = this->createNewClient();
mongocxx::client *cli3 = this->createNewClient();
auto db1 = cli1["myAppDB"];
auto db2 = cli2["myAppDB"];
auto db3 = cli3["myAppDB"];
编译器说:
PATH/Database.cpp:31:20: error: array subscript is not an integer
auto db1 = cli1["myAppDB"];
^~~~~~~~~~
PATH/Database.cpp:32:20: error: array subscript is not an integer
auto db2 = cli2["myAppDB"];
^~~~~~~~~~
PATH/Database.cpp:33:20: error: array subscript is not an integer
auto db3 = cli3["myAppDB"];
^~~~~~~~~~
3 errors generated.
目标是使用指针动态创建客户端,并在需要新客户端时调用 createNewClient() 函数。
mongocxx::client *Database::createNewClient()
{
mongocxx::client *cli = new mongocxx::client();
return (cli);
}
如果我喜欢它,它会起作用:
mongocxx::client conn;
auto db = conn["myAppDB"];
我不明白为什么?这种情况下的“[]”是什么?
您尝试在指针上调用[] 运算符,这显然不起作用。您应该取消引用指针并改为在对象实例上调用它:
auto d = (*cli1)["myAppDB"];