从c ++类返回的指针的地址

时间:2014-11-01 13:42:32

标签: c++

我正在用c ++编写二进制搜索树程序。我有一个节点类如下:

template<typename T>
class BinaryTreeNode{
private:
T _data;
BinaryTreeNode<T>* _left;
BinaryTreeNode<T>* _right;

public:
T& data() { return _data; }
const T& data() const { return _data; }

BinaryTreeNode<T>* left() { return _left; }
const BinaryTreeNode<T>* left() const { return _left; }

BinaryTreeNode<T>* right() { return _right; }
const BinaryTreeNode<T>* right() const { return _right; }

};

在我的二分查找树类中,我有一个添加节点的方法,如下所示

 template<typename T>
void BinarySearchTree<T>::_push(BinaryTreeNode<T>** root ,BinaryTreeNode<T>* node){
    if(*root == NULL){
        *root = node;
    }else{
        if(node->data() < (*root)->data()){
            _push(&((*root)->left()), node);
        }else{
            _push(&((*root)->right()), node);
        }
     }
}

我在_push()中遇到以下错误:

binary_tree.h:32:9: error: lvalue required as unary ‘&’ operand
_push(&((*root)->left()), node);
      ^
binary_tree.h:36:9: error: lvalue required as unary ‘&’ operand
_push(&((*root)->right()), node);
      ^

这种语法有问题吗?任何人都可以在这里解释一下有什么问题吗?

1 个答案:

答案 0 :(得分:4)

_push(&((*root)->left()), node)

您正在尝试从左侧函数返回临时地址。

一个好的建议总是在将类转换为模板类之前测试您的类的设计问题。这样模板可以节省一些阴险的责任。