对类型 'int' 的非常量左值引用无法绑定到类型 'int' 的临时

non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'

本文关键字:int 类型 绑定 常量 非常 引用      更新时间:2023-10-16

这是我的二叉树节点实现。

template<typename T> class node{
    public:
        explicit node():data(0), left(NULL), right(NULL){}
        explicit node(const T& data):data(data),left(NULL), right(NULL){}
        template<typename E> friend class bst;
    private:
        T& data;
        node<T>* left;
        node<T>* right;
};

这是二进制搜索树。

template<typename T> class bst{
    public:
        bst():root(NULL){}
        bst(node<T>* root):root(root){}
private:
        node<T>* root;
};

调用类执行类似的操作。

int main(){
    node<int>* root = new node<int>(17);
    bst<int>* t = new bst<int>(root);

    t->insert(root,21);
    t->insert(root,12);
    t->insert(root, 9);
    delete t;
}

我总是犯错误。

./node.hpp:3:19: error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
                explicit node():data(0), left(NULL), right(NULL){}

有人能帮我理解一下,这里到底出了什么问题吗。

T& data;

这是你的问题。这应该是一个T。没有理由将其作为参考。在默认构造函数中,您尝试为其分配一个临时值(文本0),由于它是一个引用类型,因此无法为其指定临时值。

考虑到0是一个int,并且您的类型被设计为可以与所有类型一起使用,文字0的默认值仍然是一个糟糕的选择。您应该考虑使用一个更多态的值,如T(),或者在注释或文档中明确声明类型必须从int转换。