我正在编写一个服务器端 C++ 音乐应用程序。我被数据库部分困住了,我选择 MongoDB,而且我不是 C++ 的老大。
我创建了一个数据库类来存储 MongoDB 唯一实例,我想像这样动态创建多个 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"];