[英]Having trouble implementing a const_iterator for a binary tree C++
[英]C++, having issues using const_iterator to make operator=
當我編寫以下代碼時,會發生編譯錯誤:
const_iterator it = cp.begin();
const_iterator
是我自己的const iterator
類。
cp
是ConjuntoPreguntas
類的對象(請參見下文)。
錯誤是:
mainprueba.cpp:30:6: error: no match for ‘operator=’ (operand types are ‘ConjuntoPreguntas::const_iterator’ and ‘ConjuntoPreguntas::iterator’)
cit = CP.begin();
^
mainprueba.cpp:30:6: note: candidate is:
In file included from mainprueba.cpp:2:0:
conjuntopreguntas.h:258:21: note: ConjuntoPreguntas::const_iterator& ConjuntoPreguntas::const_iterator::operator=(const ConjuntoPreguntas::const_iterator&)
const_iterator& operator=(const const_iterator& cit){
^
conjuntopreguntas.h:258:21: note: no known conversion for argument 1 from ‘ConjuntoPreguntas::iterator’ to ‘const ConjuntoPreguntas::const_iterator&’
編碼:
class ConjuntoPreguntas{
private:
map<int,Pregunta> preguntas;
public:
class const_iterator;
class iterator{
private:
map<int,Pregunta>::iterator it;
public:
iterator & operator++(){
++it;
}
iterator & operator--(){
--it;
}
pair<const int,Pregunta> &operator *(){
return *it;
}
bool operator ==(const iterator &i){
return i.it==it;
}
bool operator !=(const iterator &i){
return i.it!=it;
}
friend class ConjuntoPreguntas;
friend class const_iterator;
};
class const_iterator{
private:
map<int,Pregunta>::iterator it;
public:
const_iterator(){
}
const_iterator & operator++(){
++it;
}
const_iterator & operator--(){
--it;
}
pair<const int,Pregunta> &operator *(){
return *it;
}
bool operator ==(const const_iterator &i){
return i.it==it;
}
bool operator !=(const const_iterator &i){
return i.it!=it;
}
const_iterator& operator=(const const_iterator& cit){
}
friend class ConjuntoPreguntas;
};
iterator begin(){
iterator i;
i.it=preguntas.begin();
return i;
}
iterator end(){
iterator i;
i.it=preguntas.end();
return i;
}
/* other code, irrelevant to the problem */
};
如果有人可以幫助我,我將非常感激。
您最直接的問題是因為您沒有begin
的const
版本:
const_iterator begin() const
{
const_iterator i;
i.it = preguntas.begin();
return i;
}
但是,然后您的const_iterator
類使用map的迭代器,這將導致另一個問題。
如果您正在編寫一個看起來像容器的類,那么除了編寫const正確的迭代器和const_iterator類並提供const正確的成員之外,別無其他。
但是,如果您沒有編寫容器,則可能不希望這樣做。 最好的情況是為該類提供一個與容器無關的接口,例如,您在其中提供有意義的名稱,而不是直接進行容器訪問。 或者通過映射const_iterator
提供僅const訪問(不要編寫您自己的迭代器類)。
如果要將std容器完全封裝在類中(艱巨且通常是不必要的任務),則需要確保還定義了所有轉換。 特別是,標准容器迭代器具有一個構造函數,該構造函數從迭代器創建const_iterator(但反之則不行!)。 您也必須自己創建它。
但是,更好的設計選擇是僅公開成員map
變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.