الرجوع إلى مؤشر في وظيفة عضو C ++
-
01-10-2019 - |
سؤال
أنا أكتب وظيفة عضو تستخدم مؤشر متغير الأعضاء كمؤشر. ومع ذلك ، أريد الرجوع إلى المؤشر داخل الوظيفة بحتة من أجل قابلية القراءة. مثل ذلك:
/* getNext will return a pos object each time it is called for each node
* in the tree. If all nodes have been returned it will return a Pos
* object (-1, -1).
* TODO: Add a lock boolean to tree structure and assert unlocked for
* push/pop.
*/
Pos BTree::getNext () const
{
BTreeNode*& it = this->getNextIter;
while (it)
{
if (it->visited)
{
/* node has been visited already, visit an unvisited right
* child node, or move up the tree
*/
if ( it->child [BTREE_RIGHT] != NULL
&& !it->child [BTREE_RIGHT]->visited)
{
it = it->child [BTREE_RIGHT];
}
else
{
it = it->parent;
}
}
else
{
/* if unvisited nodes exist on the left branch, iterate
* to the smallest (leftmost) of them.
*/
if ( it->child [BTREE_LEFT] != NULL
&& !it->child [BTREE_LEFT]->visited)
{
for (;
it->child [BTREE_LEFT] != NULL;
it = it->child [BTREE_LEFT]) {}
}
else
{
it->visited = 1;
return it->pos;
}
}
}
it = this->root;
this->setTreeNotVisited (this->root);
return Pos (-1, -1);
}
هذا هو ما سأذهب إليه بشكل أساسي ، حيث يكون هذا-> getNextiter هو btreenode*. ومع ذلك أحصل على الخطأ:
btree.cpp:238: error: invalid initialization of reference of type
'DataTypes::BTreeNode*&' from expression of type 'DataTypes::BTreeNode* const'
ما هو بناء الجملة المناسب لهذا النوع من الأشياء؟
هتافات،
ريس
المحلول
وظيفة العضو الخاص بك const
-مؤهلة ، لذلك لا يمكنك تعديل متغير العضو getNextIter
. تحتاج إلى استخدام مرجع const:
BTreeNode * const & it = getNextIter;
ومع ذلك ، في وظيفتك ، تقوم بتعديل it
, ، لذا ربما تحتاج إلى إزالة const
-التأهيل من وظيفة العضو أو جعل getNextIter
متغير عضو mutable
.
عندما يكون لديك وظيفة عضو const
-مؤهلة ، كل غيرmutable
متغيرات الأعضاء هي const
-مؤهلة داخل وظيفة العضو ، ولهذا السبب يوضح المترجم أنه عند محاولة استخدامه getNextIter
بداخل getNext()
, ، لديه نوع من DataTypes::BTreeNode* const
(لاحظ ال const
).