簡體   English   中英

對“ int”類型的非常量左值引用不能綁定到“ int”類型的臨時對象

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

這是我對二叉樹的節點實現。

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是一個整數,並且您的類型被設計為可與所有類型一起使用,立即數0對於其默認值仍然不是一個好的選擇。 您應該考慮在注釋或文檔中使用更多的多態值,例如T()或顯式聲明該類型必須可以從int轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM