我正在尝试创建自己的翻译器。这是大学作业。我的类翻译器中需要一个迭代器。
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;
};
};
我正在尝试重载 operator*()
;
这是代码。
pair <string, Word>& Translator::iterator::operator*()
{
return (*itm);
}
错误:
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>
最佳答案
映射的键是常量,所以值类型是pair<const string, Word>
.
某些类型别名可能会使代码更友好:
typedef map <string,Word> map_type;
typedef map_type::value_type value_type;
value_type &operator*();
关于c++ - C++ 中的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27245982/