对指针的引用

Reference to a pointer

本文关键字:引用 指针      更新时间:2023-10-16

我只是在两个陈述之间有点困惑。

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

要打印值,可以通过

cout << a << *p << r;

以上所有内容都将打印 a 的值,但如何打印,这就是我想知道的。

  1. 现在这就是对指针的引用的定义

    int i = 42;
    int *p;
    int *&r = p; //declares reference r to pointer p
    r = &i; //stores the address of i in pointer p
    

我只是想了解为什么第一个没有定义对指针的引用。

在此代码片段中

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 

表达式*p生成对象的左值a因为指针p指向该对象。所以这个宣言

int &r = *p;

声明对同一对象的引用,a通过指针p间接访问对象。

从C++标准(5.3.1 一元运算符)

1 一元 * 运算符执行间接寻址:其表达式 它应用于指向对象类型的指针,或指向 函数类型,结果是引用对象的左值或 表达式指向的函数。如果表达式的类型 是"指向 T 的指针",结果的类型是"T"。[ 注:间接 通过指向不完整类型(CV void 除外)的指针是有效的。这样获得的左值可以以有限的方式使用(例如,初始化引用);此左值不得转换为 PR值,见 4.1。—尾注 ]

问题中介绍的两个代码片段之间的区别在于,在第一个代码片段中,通过指针使用间接寻址声明了对类型int(int a = 42; ) 对象的引用。而在第二个代码片段中,声明了对指针 (int *p;) 的引用。

让我们分解一下(从右到左):

int &r = *p; 

*p  

de 引用指针

而这个

int& r

是参考声明

在最后

int& r = *p;

相当于

int& r = a;

例:

int main()
{
int a = 42;
int *p = &a; //declares pointer p to a
int &r = *p;
cout << "a: " << a << endl;
cout << "r: " << r << endl;
cout << "changing a:" << endl;
a = 17;
cout << "a: " << a << endl;
cout << "r: " << r << endl;
cout << "changing r:" << endl;
r = 0;
cout << "a: " << a << endl;
cout << "r: " << r << endl;
cin.get();
return 0;
}

这是因为在第一种情况下,您刚刚声明了对 int 的常规引用,并为其分配了*p,这是一个 int。 *p 不是指针,而是指针p指向的值 - 在这种情况下,它只是a的值。