在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'
这种事情的适当语法是什么?
干杯,
Rhys
解决方案
您的会员功能是 const
- 资格,因此您无法修改成员变量 getNextIter
. 。您需要使用const参考:
BTreeNode * const & it = getNextIter;
但是,在您的功能中,您正在修改 it
, ,因此,您可能需要删除 const
- 从成员函数合格或制作 getNextIter
成员变量 mutable
.
当您具有成员函数时 const
- 合格,所有非 -mutable
成员变量是 const
- 成员功能内部合格的,因此编译器为什么要报告您尝试使用时 getNextIter
代替 getNext()
, ,有一种类型 DataTypes::BTreeNode* const
(注意 const
).
不隶属于 StackOverflow