【发布时间】:2021-09-23 07:27:49
【问题描述】:
以这种方式编写代码时...
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node(int data) {
this->data = data;
}
};
void display(const Node* &p){
cout<<p->data<<endl;
}
int main(){
Node *p = new Node(10);
display(p);
return 0;
}
我收到以下错误。
error: cannot bind non-const lvalue reference of type 'const Node*&' to an rvalue of type 'const Node*'
但是,如果将函数 display 的参数 const Node* &p 更改为 Node* &p,则此方法有效。
有人可以向我解释这是如何工作的吗?
【问题讨论】:
-
为什么还要使用
const Node* &而不是const Node*或const Node&?您似乎不想修改p在display函数中指向的位置。 -
@Zaiborg ,是的,我不想修改指针 p ,它是
display函数中指向的内存位置。