c++ - 在 C++ 成员函数中引用指针

标签 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);
}

这基本上就是我想要的,其中 this->getNextIter 是一个 BTreeNode*。但是我得到了错误:

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

这种事情的合适语法是什么?

干杯,

瑞斯

最佳答案

您的成员函数是 const 限定的,因此您不能修改成员变量 getNextIter。您需要使用常量引用:

BTreeNode * const & it = getNextIter;

但是,在您的函数中,您修改了,因此您可能需要从成员函数中删除const 限定或使getNextIter 成员变量 mutable.

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

关于c++ - 在 C++ 成员函数中引用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3655888/

相关文章:

c++未找到错误c2678的运算符

c++ - DirectX11 移动对象矩阵顺序

c++ - 使用抽象来制作翻译器

c++ - 我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?

c++ - 使用 std::sort 根据数据类型中包含的整数值对混合数据类型 vector 进行排序有多安全?

c - 尝试仅使用 C 复制结构中的 C 字符串

c++11 - 在 C++ 中将 NULL 转换为 SomeType* 有什么用?

c++ - 在引用初始化中构造的对象

c++ - 在 C++ 方法签名中 * 是什么意思?

c++ - 重载括号运算符作为成员函数