이 문제와 관련된 다른 스레드를 읽었지만 내 문제의 해결책은 제공되지 않았습니다. 나는 너희들이 나에게 아이디어 나 충고를 줄 수 있기를 바란다.const가 아닌 클래스에 대해 const_iterator를 호출하는 방법은 무엇입니까?
Map
이라는 클래스를 구현하려고합니다. 2 개의 반복자 - iterator
과 const_iterator
을 포함해야합니다.
나는 그들을 구현 - iterator
상속을 const_iterator
에서, 그리고 Map
클래스 I는 다음과 같은 기능이 : 우리가 구현하는 데 필요한 상황을 확인하기 위해 예를 들어 파일을 주어진
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
합니다. msi
이후
Map<std::string,int> msi;
...
// print map
for(Map<std::string,int>::const_iterator it = msi.begin(); it != msi.end(); ++it) {
// more stuff here
}
는 const가 아닌지도 인스턴스, 의도하지 않은 행동의 결과로 msi.begin()
iterator begin()
호출하지 const_iterator begin() const
입니다 : 거기에, 다음과 같은 코드가있다.
예제 파일이 괜찮다고 가정하면 어떻게해야합니까? msi.begin()
은 올바른 const_iterator
함수를 호출합니까? (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;
}
};
//..
}
정확하게? – Yakk