help!什么错误?

rookie001 2008-11-19 02:23:35
template<class T>
int BinaryTree<T>::Insert (const int &value, BinaryNode<T> *& temp){
if(temp==0){temp=new BinaryNode<T> (value);return 1;}
else if(value<temp->data)return Insert(value,temp->left);
else if(value>temp->data)return Insert(value,temp->right);
return 0;
}

//BinaryNode<T> * GetRoot() const{return root;}

main 函数里:
BinaryTree<int> t(1);
for(int i=0;i<4;i++)t.Insert(i,t.GetRoot());

出现错误:error C2664: 'Insert' : cannot convert parameter 2 from 'const class BinaryNode<int> *' to 'class BinaryNode<int> *& '
A reference that is not to 'const' cannot be bound to a non-lvalue
...全文
81 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
rookie001 2008-11-19
  • 打赏
  • 举报
回复
我这样写貌似有点问题:前序的:
template<class T>
int BinaryNode<T>::PreOrderNum (const BinaryNode<T>* key,int &num){

if(key==this) return num;
num++;
if(left!=0)left->PreOrderNum(key,num);
if(right!=0)right->PreOrderNum(key,num);
}
hhyttppd 2008-11-19
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 rookie001 的回复:]
顺便问一下,求某个结点的中序遍历序号,怎样较好?
[/Quote]

遍历一次,记下序号。。。
rookie001 2008-11-19
  • 打赏
  • 举报
回复
顺便问一下,求某个结点的中序遍历序号,怎样较好?
就呆在云上 2008-11-19
  • 打赏
  • 举报
回复
int BinaryTree <T>::Insert (const int &value, const BinaryNode <T> *& temp)

传入参数失败,const-》非const明显不行撒
反过来是可以的
cnmghi 2008-11-19
  • 打赏
  • 举报
回复
BinaryNode <T> * GetRoot() const{return root;}

int BinaryTree <T>::Insert (const int &value, BinaryNode <T> *& temp)

Insert(i,t.GetRoot());

出现错误:error C2664: 'Insert' : cannot convert parameter 2 from 'const class BinaryNode <int> *' to 'class BinaryNode <int> *& '

说得很清楚,关键在你把一个常量指针传给一个指向指针的非常量引用,这样是肯定不对的,应该这么改:
int BinaryTree <T>::Insert (const int &value, const BinaryNode <T> *& temp)
hhyttppd 2008-11-19
  • 打赏
  • 举报
回复
const class BinaryNode <int> *
class BinaryNode <int> *&

如果你确信GetRoot返回的对象不是临时对象并且不是常量(可以修改)
你可用const_cast去掉const属性
或者你修改Insert的接口
如:

BinaryTree <int> t(1);
for(int i=0;i <4;i++)
{
BinaryNode* root = const_cast<BinaryNode*>(t.GetRoot());
t.Insert(i,root);
}

64,676

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧