【发布时间】:2014-01-27 20:27:23
【问题描述】:
我阅读了一些与此问题相关的其他主题,但没有为我的问题提供解决方案。希望大家能给我一些意见或建议。
我正在尝试实现这个名为Map 的类。它应该包含 2 个迭代器 - iterator 和 const_iterator。
我已经实现了它们 - iterator 继承自 const_iterator,并且在 Map 类中我具有以下功能:
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
我们获得了一个示例文件,以了解实现所需的内容。 里面有如下代码:
Map<std::string,int> msi;
...
// print map
for(Map<std::string,int>::const_iterator it = msi.begin(); it != msi.end(); ++it) {
// more stuff here
}
由于 msi 是一个非常量 Map 实例,msi.begin() 调用 iterator begin() 而不是 const_iterator begin() const,从而导致意外行为。
假设示例文件没问题,我该如何让msi.begin() 调用正确的const_iterator 函数? (考虑到它,迭代器的类型是const_iterator)。
编辑:关于自动转换的讨论,我决定添加我的迭代器类,请指出我的错误。
class Map {
//...
public:
class const_iterator {
private:
Node* currNode;
public:
const_iterator(Node* cur_node = NULL) : currNode(cur_node) {}
const_iterator& operator++() {
currNode = currNode->next;
return *this;
}
const_iterator operator++(int) {
const_iterator old = *this;
++(*this);
return old;
}
bool operator!=(const_iterator const& curr) {
return !(*this == curr);
}
string operator*() {
// this might cause memory leak
string toString(this->currNode->key);
std::stringstream s;
int tmp = this->currNode->value;
s << tmp;
string secondString(s.str());
toString = toString + ":" + secondString;
return toString;
}
bool operator==(const_iterator const& curr) {
return this->currNode == curr.currNode;
}
void operator=(const_iterator target) {
this = target;
}
//void operator=(Node* target) {
// this->currNode = target;
//}
};
class iterator : public const_iterator {
private:
Node* currNode;
public:
iterator(Node* cur_node = NULL) : currNode(cur_node) {}
iterator& operator++() {
currNode = currNode->next;
return *this;
}
iterator operator++(int) {
iterator old = *this;
++(*this);
return old;
}
bool operator==(iterator const& curr) {
return *this == curr;
}
bool operator!=(iterator const& curr) {
return !(*this == curr);
}
string operator*() {
// this might cause memory leak
string toString(this->currNode->key);
std::stringstream s;
int tmp = this->currNode->value;
s << tmp;
string secondString(s.str());
toString = toString + ":" + secondString;
return toString;
}
void operator=(iterator target) {
this = target;
}
};
//..
}
【问题讨论】:
-
为什么调用
iterator版本不好?
标签: c++ templates iterator constants