"非常量引用的初始值必须为左值"this指针无法以引用的形式传递给友元函数

DZGodly 2018-01-02 08:11:25
程序部分代码如下,错误提示如文末图片所示;大佬们求救,下周交作业了! help!!!
typedef class BookTree {
private:
BorrowedBook book;
BookTree* lchild;
BookTree* rchild;
public:
void in();
friend void insert(BookTree*&, string&, bool&);
};
void insert(BookTree*& t,string& id,bool& flag) {
if (flag) return;
if (t != NULL) {
if (t->book.id == id) {
cout << "-----此书已存在,库存+1-----" << endl;
t->book.rest++;
t->book.stock++;
flag = true;
}
else if (t->book.id > id)
insert(t->lchild, id, flag);
else insert(t->rchild, id, flag);
}
else {
t = new BookTree;
cout << "请输入书名:";
cin >> t->book.name; cout << endl;
cout << "请输入作者:";
cin >> t->book.auth; cout << endl;
t->book.rest = 1;
t->book.stock = 1;
cout << "-----存入成功-----" << endl;
flag = true;
}
}

void BookTree::in() {
cout << "请输入书号:";
string id;
cin >> id;
cout << endl;
bool flag = false;
insert(this, id, flag);
}

...全文
409 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
真相重于对错 2018-01-04
  • 打赏
  • 举报
回复
insert里面改一下就可以了,没必要修改t 指针 else if (t->book.id > id) { if(t->lchild!=NULL) insert(t->lchild, id, flag); else { BookTree * tmp = new BookTree; tmp->....= t->lchild=tmp; } } else{ insert(t->rchild, id, flag); //同理 }
paschen 版主 2018-01-03
  • 打赏
  • 举报
回复
this指针是常量,不能修改,insert函数实际不需要第一个参数
大风哉 2018-01-03
  • 打赏
  • 举报
回复
我觉得this指针是常量不能修改是对的,而在"void insert(BookTree*& t,string& id,bool& flag);"函数签名中对于BookTree*类型变量的引用可能导致对于此变量的改变,所以会报这个错。比如函数外部有这样一个指针变量"BookTree* pTree",传到insert函数中也是这个pTree变量,函数中的t只不过是这个pTree的别名,函数内部可以用这样的语句来改变pTree的值:"t = new BookTree;"。 这报的错确实读着拗口,实际内容应该就是"和this指针作为常量不能修改"这个情况矛盾。 你可以在"void insert(BookTree*& t,string& id,bool& flag);"的BookTree前加上const使这个引用不能被修改:void insert(const BookTree*& t,string& id,bool& flag); 或者不直接传this指针,而是通过一个临时指针变量来传: BookTree* pTemp = (BookTree*)this; insert(pTemp, id, flag);
大风哉 2018-01-03
  • 打赏
  • 举报
回复
我觉得大家回答有点偏题,楼主是想问为什么会出现这个问题的,而不是说怎么去解决这个问题。 解决这个问题是后面一步需要做的。
paschen 版主 2018-01-03
  • 打赏
  • 举报
回复
引用 4 楼 朴实的农民Z的回复:
[quote=引用 2 楼 paschen 的回复:] this指针是常量,不能修改,insert函数实际不需要第一个参数
但是insert函数是一个递归函数,如果不传入this作为参数的话就没办法实现递归功能了啊[/quote] 那你看下这样呢: BookTree* p = (BookTree*)this; insert(p, id, flag);
DZGodly 2018-01-03
  • 打赏
  • 举报
回复
引用 2 楼 paschen 的回复:
this指针是常量,不能修改,insert函数实际不需要第一个参数
但是insert函数是一个递归函数,如果不传入this作为参数的话就没办法实现递归功能了啊
DZGodly 2018-01-03
  • 打赏
  • 举报
回复
引用 1 楼 sdghchj 的回复:
去掉引用符号。this的类型Type* const,不能传给Type*& void insert(BookTree*& t,string& id,bool& flag)
去掉&的话,insert函数就不能对this指针指向的内容进行修改了啊
sdghchj 2018-01-02
  • 打赏
  • 举报
回复
去掉引用符号。this的类型Type* const,不能传给Type*& void insert(BookTree*& t,string& id,bool& flag)

64,648

社区成员

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

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