Domanda

Sto scrivendo una funzione di membro che utilizza un puntatore variabile membro come un iteratore. Comunque voglio fare riferimento il puntatore all'interno della funzione puramente per amor di leggibilità. In questo modo:

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

Questo è fondamentalmente quello che sto andando per, dove this-> getNextIter è un BTreeNode *. Tuttavia ho l'errore:

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

Qual è la sintassi appropriata per questo genere di cose?

Saluti,

Rhys

È stato utile?

Soluzione

La vostra funzione di membro è const qualificati, quindi non è possibile modificare la getNextIter variabile membro. È necessario utilizzare un riferimento const:

BTreeNode * const & it = getNextIter;

Tuttavia, nella funzione, è possibile modificare it, così invece probabilmente è necessario rimuovere il const-qualificazione dalla funzione di membro o fare il getNextIter variabile membro mutable.

Quando si dispone di una funzione di membro che è const qualificato, tutte le variabili membro non mutable sono const qualificato all'interno della funzione membro, quindi, perché i rapporti compilatore che quando si tenta di utilizzare getNextIter all'interno di getNext(), ha un tipo di DataTypes::BTreeNode* const (notare il const).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top