引用C ++成员函数中的指针

时间:2010-09-07 04:54:14

标签: c++ pointers reference member-variables

我正在编写一个使用成员变量指针作为迭代器的成员函数。但是我想在函数中引用指针纯粹是出于可读性的考虑。像这样:

/* 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'

这种事情的恰当语法是什么?

干杯,

里斯

1 个答案:

答案 0 :(得分:3)

您的会员功能是const - 合格,因此您无法修改成员变量getNextIter。您需要使用const引用:

BTreeNode * const & it = getNextIter;

但是,在您的函数中,您修改了it,因此您可能需要从成员函数中删除const - 限定条件或创建getNextIter成员变量{{1} }。

当你有一个成员函数mutable - 限定时,所有非const成员变量都是mutable - 在成员函数内部是合格的,因此编译器报告的时候您尝试在const内使用getNextIter,其类型为getNext()(请注意DataTypes::BTreeNode* const)。