【问题标题】:Error: no viable overloaded operator[]错误:没有可行的重载运算符 []
【发布时间】:2015-06-24 16:08:00
【问题描述】:

这是我的一些代码:

#include "pugi/pugixml.hpp"

#include <iostream>
#include <string>
#include <map>
int main() {
    pugi::xml_document doca, docb;
    std::map<std::string, pugi::xml_node> mapa, mapb;

    if (!doca.load_file("a.xml") || !docb.load_file("b.xml"))
        return 1;

    for (auto& node: doca.child("site_entries").children("entry")) {
        const char* id = node.child_value("id");
        mapa[new std::string(id, strlen(id))] = node;
    }

    for (auto& node: docb.child("site_entries").children("entry"))
        const char* idcs = node.child_value("id");
        std::string id = new std::string(idcs, strlen(idcs));
        if (!mapa.erase(id)) {
            mapb[id] = node;
        }
    }

编译时出现此错误:

src/main.cpp:16:13: error: no viable overloaded operator[] for type 'std::map<std::string, pugi::xml_node>'
        mapa[new std::string(id, strlen(id))] = node;

【问题讨论】:

  • new std::string... --> std::string
  • 你是java人吗?因为我在这里感觉Java:std::string id = new std::string(idcs, strlen(idcs));。你不要 new C++ 中的局部变量。
  • 现在,你不会在 C++ 中new 任何东西

标签: c++ c++11


【解决方案1】:

您的类型不匹配。 mapa 的类型为:

std::map<std::string, pugi::xml_node> mapa,
         ^^^^^^^^^^^^

但你正在做:

mapa[new std::string(id, strlen(id))] = node;
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         string*

std::map 有两个 operator[] 重载:

T& operator[](const Key& );
T& operator[](Key&& );

在您的情况下,Keystd::string。但是您试图传入std::string*,因为它没有转换为std::string - 因此您会收到“没有可行的重载operator[]”的错误。

你的意思是:

mapa[id] = node;

此行的相同注释:

std::string id = new std::string(idcs, strlen(idcs));

C++ 不是 Java,你只需这样做:

std::string id(idcs, strlen(idcs));

或者简单地说:

std::string id = idcs;

【讨论】:

  • 非常感谢。这似乎标记了这些错误:src/main.cpp:21:24: error: use of undeclared identifier 'idcs' std::string id(idcs, strlen(idcs)); ^ src/main.cpp:23:24: error: use of undeclared identifier 'node' mapb[id] = node; 这与新代码有关还是单独的问题?
  • @Jimmy 你之前就行声明了(const char* idcs = node.child_value("id");)?
  • 类型不匹配..同样的错误。我们都犯了愚蠢的错误。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 2021-11-03
  • 2018-03-14
  • 1970-01-01
  • 2017-05-03
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
相关资源
最近更新 更多