Pregunta

Estoy escribiendo una función miembro que utiliza un puntero variable miembro como un iterador. Sin embargo, quiero hacer referencia al puntero dentro de la función puramente por el bien de la legibilidad. De esta manera:

/* 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);
}

Esto es básicamente lo que voy, dónde this-> getNextIter es una BTreeNode *. Sin embargo, me sale el error:

    btree.cpp:238: error: invalid initialization of reference of type
'DataTypes::BTreeNode*&' from expression of type 'DataTypes::BTreeNode* const'

¿Cuál es la sintaxis adecuada para este tipo de cosas?

Saludos,

Rhys

¿Fue útil?

Solución

Su función miembro es const cualificado, por lo que no se puede modificar la variable miembro getNextIter. Es necesario utilizar una referencia constante:

BTreeNode * const & it = getNextIter;

Sin embargo, en su función, modifica it, así que en vez es probable que tenga que quitar la const-calificación de la función miembro o hacer que la variable miembro getNextIter mutable.

Cuando se tiene una función miembro que es const cualificado, todas las variables miembro no mutable están dentro const calificado de la función miembro, por lo tanto, por qué los informes del compilador que cuando intenta utilizar el interior getNextIter de getNext(), tiene una tipo de DataTypes::BTreeNode* const (nótese el const).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top