对类型 '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
是一个int,并且您的类型被设计为可以与所有类型一起使用,文字0
的默认值仍然是一个糟糕的选择。您应该考虑使用一个更多态的值,如T()
,或者在注释或文档中明确声明类型必须从int转换。
相关文章:
- 为什么 int 类型的枚举类值不能用作 int
- 如何将文本文件的特定行读取到 int 类型的数组中C++?
- int* 和 int[] 类型对二进制运算符 + 的操作数无效
- 比较两个整数在C++中与未知 int 类型的相等性
- 二进制'operator+' 'int*'和'int*'类型的无效操作数
- 使用元编程选择 int 类型,将生成错误
- 从数组创建 Mat 时,'cv::Mat' 和 'int' 类型不兼容
- 复制初始化 - 从 'int' 类型转换为非标量类型
- 初始化cv :: mat ::具有int类型的定义大小的人
- 处理代码重新定义int类型(uint16_t,int16_t等),并不喜欢它
- 为什么没有"int"类型声明时输出不同?
- 在大型程序中将长变量更改为 int 类型
- 无法将 int 类型转换为时间类型(我的类类型)
- C++:无法在按位函数后将 int 类型设置为非标量
- 无法分配给INT类型的成员[10]
- C++ cin 将字符串读取到 int 类型中返回 0
- 为什么 decltype((i)) 是引用类型,而 decltype(i+0) 是 int 类型
- 使用4用于循环的4矩阵上的数组下标的“ int [int]类型”
- std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?
- 正在施放带有“ Int”类型的临时性