gpt4 book ai didi

c++ - 对指针的引用

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:25:02 25 4
gpt4 key购买 nike

我只是对两个陈述有点困惑。

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;

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

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

1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is “pointer to T”, the type of the result is “T”. [ Note: Indirection through a pointer to an incomplete type (other than cv void) is valid. The lvalue thus obtained can be used in limited ways (to initialize a reference, for example); this lvalue must not be converted to a prvalue, see 4.1. —end note ]

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

关于c++ - 对指针的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44046625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com