Reputation: 215
This is my node implementation for a binary tree.
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;
};
This is the binary search tree.
template<typename T> class bst{
public:
bst():root(NULL){}
bst(node<T>* root):root(root){}
private:
node<T>* root;
};
The calling class does something like this.
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;
}
I keep getting the error.
./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){}
Can someone please help me understand, what exactly is the issue here.
Upvotes: 0
Views: 7176
Reputation: 70267
T& data;
There's your problem. That should be a T
. There's no reason to make it a reference. In your default constructor, you try to assign a temporary value (the literal 0
) to it, and since it's a reference type you can't give it a temporary value.
The literal 0
is still a poor choice for its default value, considering that 0
is an int, and your type is designed to work with all types. You should consider using a more polymorphic value, like T()
or explicitly declaring that the type must be convertible from int, in a comment or documentation.
Upvotes: 1