C++中的迭代器

Mav*_*k94 5 c++ iterator overloading operator-keyword c++11

我正在尝试创建自己的翻译器.这是大学的工作.我的班级译者需要一个迭代器.

class Translator
{
private:
    map <string,Word> translator;

public:
    class iterator
    {
       friend class Translator;
        private:
            map<string,Word>::iterator itm;

        public:
            iterator operator++();
            pair <string,Word> &operator*();
            bool operator==(const iterator &it)const;
    };
};
Run Code Online (Sandbox Code Playgroud)

我想超载operator*();

这是代码.

pair <string, Word>& Translator::iterator::operator*()
{
  return (*itm);
}
Run Code Online (Sandbox Code Playgroud)

错误:

invalid initialization of reference of type ‘std::pair<std::basic_string<char>, Word>&’ from expression of type ‘std::pair<const std::basic_string<char>, Word>

Mik*_*our 9

地图的键是常量,因此值类型是pair<const string, Word>.

某些类型的别名可能会使代码更友好:

typedef map <string,Word> map_type;
typedef map_type::value_type value_type;

value_type &operator*();
Run Code Online (Sandbox Code Playgroud)