dal*_*ngh 1 c++ pointers reference
我只是在两个陈述之间有点困惑.
1.
int a = 42;
int *p = &a; //declares pointer p to a
int &r = *p; //this is not the way to declare a reference to a pointer, but what does this statement do
Run Code Online (Sandbox Code Playgroud)
要打印价值,可以通过以下方式完成
cout << a << *p << r;
Run Code Online (Sandbox Code Playgroud)
以上所有将打印a的值,但是如何,这就是我想知道的.
现在,这是如何定义对指针的引用
int i = 42;
int *p;
int *&r = p; //declares reference r to pointer p
r = &i; //stores the address of i in pointer p
Run Code Online (Sandbox Code Playgroud)我只想了解为什么第一个没有定义对指针的引用.
在此代码段中
int a = 42;
int *p = &a; //declares pointer p to a
int &r = *p; //this is not the way to declare a reference to a pointer, but what does this
Run Code Online (Sandbox Code Playgroud)
表达式*p产生对象的左值,a因为指针p指向对象.所以这个宣言
int &r = *p;
Run Code Online (Sandbox Code Playgroud)
a使用通过指针间接访问对象来声明对同一对象的引用p.
来自C++标准(5.3.1一元运算符)
1一元*运算符执行间接:它所应用的表达式应该是指向对象类型的指针,或指向函数类型的指针,结果是一个引用表达式指向的对象或函数的左值.如果表达式的类型是"指向T的指针",则结果的类型为"T".[注意:通过指向不完整类型(cv void除外)的指针间接是有效的. 由此获得的左值可以以有限的方式使用(例如,初始化参考) ; 这个左值不能转换为prvalue,见4.1. - 尾注]
问题中提到的两个代码片段之间的区别在于,在第一个代码片段中,int通过指针使用间接方式声明了对类型(int a = 42;)的对象的引用.在第二个代码片段中,声明了对指针的引用(int*p;).