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