非 const 引用不能绑定到右值,这是您尝试对 DT &data 参数的参数 9 执行的操作。
您需要传入一个值为9 的变量,或者您需要将参数(以及dataItem 成员,如果它是引用)更改为DT 类型按值复制到对象中。即使您将引用更改为const 以消除编译器错误,如果传入的参数是临时的(它不会在构造函数调用之后存在,所以您会遇到传入参数的生命周期问题,因此你会留下一个悬空的参考)。
这是一个小示例程序,演示了将对象中的 const 引用绑定到临时对象(从 rand() 返回的 int 值)的问题。请注意,该行为是未定义的,因此在某些情况下它可能会起作用。我在 MSVC 2008 和 MinGW 4.5.1 上使用调试版本测试了这个程序:
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
template <class KF, class DT>
class BSTreeNode {
private:
KF key;
DT const& dataItem;
BSTreeNode* left;
BSTreeNode* right;
public:
BSTreeNode(KF sKey, DT const &data, BSTreeNode *lt, BSTreeNode *rt)
: key(sKey)
, dataItem(data)
, left(lt)
, right(rt)
{}
void foo() {
printf( "BSTreeNode::dataItem == %d\n", dataItem);
}
};
BSTreeNode<int, int>* test1()
{
BSTreeNode<int, int>* p = new BSTreeNode<int, int>(5,rand(), NULL, NULL);
// note: at this point the reference to whatever `rand()` returned in the
// above constructor is no longer valid
return p;
}
int main()
{
BSTreeNode<int, int>* p1 = test1();
p1->foo();
printf( "some other random number: %d\n", rand());
p1->foo();
}
一个示例运行显示:
BSTreeNode::dataItem == 41
some other random number: 18467
BSTreeNode::dataItem == 2293724