对指针的引用
Reference to a pointer
我只是在两个陈述之间有点困惑。
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 的值,但如何打印,这就是我想知道的。
现在这就是对指针的引用的定义
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的值。
相关文章:
- C++取消引用指针.为什么会发生变化
- 深层复制具有自引用指针的类
- Visual c ++,使用字符串引用/指针调用 dll 函数
- std::unordered_map::提取引用/指针失效
- 为什么在引用指针时将 const 放在 & 符号的左侧有效,而在右侧则无效?
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 如何在 c++ 中使用带有数学运算的引用/指针?
- 了解通过引用传递取消引用指针时C++堆/堆栈分配
- 取消引用指针并立即为其分配变量,导致分段错误
- 如何获取指向类(而不是对象)的引用/指针
- 将类型参数传递给自引用指针
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 在析构函数内取消引用指针时出现分段错误
- 来自引用指针的内存泄漏
- 引用指针后面的值
- 无法取消引用指针
- 引用指针调用成员函数
- 未定义的引用指针的变量模板在clang中功能,而不是GCC
- 取消引用指针以创建数组的副本
- 有关启动引用指针的引用的问题