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

Ord*_*man 1 c++ java unordered-map

我正在尝试手动将一些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); }
}
Run Code Online (Sandbox Code Playgroud)

我的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); }
        ...
}
Run Code Online (Sandbox Code Playgroud)

在C++ 11中编译我收到以下错误:

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

我哪里出错了?

das*_*ght 11

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

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

既然storage是实例成员Item,请使用

groups.insert(w.storage, w);
Run Code Online (Sandbox Code Playgroud)

请注意,如果您通过w常量引用,您会更好:

void save(const Item& w) { groups.insert(w::storage, w); }
Run Code Online (Sandbox Code Playgroud)

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

std::unordered_map<std::string,Item> groups;
Run Code Online (Sandbox Code Playgroud)

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