在 C++ 中无效使用范围运算符

Invalid use of scope operator in C++

我正在尝试手动将一些 Java 移植到 C++ 中。

Java:

public Class Item {
    public String storage = "";
    public Item(String s, int tag) { storage = s; }
    ...
}

public class ProcessItems {
    Hashtable groups = new Hashtable();
    void save(Item w) { groups.put(w.storage, w); }
}

我的 C++:

#include<iostream>
#include<unordered_map>
#include<string>


class Item {
    public:
        std::string storage;
        Item(std::string s, int tag) { storage = s; }
        ...
}

class ProcessItems {
    public:
        std::unordered_map<std::string, std::string> *groups = new std::unordered_map<std::string, std::string>();
        void save(Item w) { groups.insert(w::storage, w); }
        ...
}

在 C++ 11 中编译时出现以下错误:

error: invalid use of ‘::’
    string, std::string> *words = new std::unordered_map<std::string, std::string>();
                                                                         ^

我哪里出错了?

在Java中,成员解析和作用域解析都是用运算符点.完成的,而在C++中,这些运算符是不同的:

  • 使用::访问命名空间的成员或class
  • 的静态成员
  • 使用.访问由引用或值表示的实例成员
  • 使用->访问指针表示的实例成员

因为 storageItem 的实例成员,所以使用

groups.insert(w.storage, w);

请注意,如果您通过 w 通过不断的参考,您会过得更好:

void save(const Item& w) { groups.insert(w::storage, w); }

您还需要将 groups 从指针更改为对象,并修复其类型以匹配您计划放入地图的内容:

std::unordered_map<std::string,Item> groups;

与 Java 不同,C++ 会将 groups 初始化为有效对象,而无需显式调用默认构造函数。