指针引用类型的序列

Sequence of a pointer reference type

关于这个问题我还有一个问题。

问题中的回答者使用int*&作为参数数据类型,但我不明白指针和引用数据类型的顺序。

在我看来,int&* 对我来说更实用,所以我尝试用它进行编译,但不允许这样做。

我想清楚这个逻辑。

我以为int*& aint*(int& a),所以它就像一个引用的指针,但显然,正好相反

为什么我不能用int&*作为指针引用的意思?

C++ 类型以名称为中心。 int*&foo 是你应该怎么想的。

首先,我们有 &foo -- foo 是参考。参考什么? *&foo -- 一个指针。指向什么的指针? int*&foo 一个整数。

原始的 C 类型规则甚至打算"demonstrate how they are used"。所以 int *fooint = *foo 的简写,是一个有效的表达式,或者 *fooint& 不是那样工作的。

Clockwise/Spiral Rule

There are three simple steps to follow:

  1. Starting with the unknown element, move in a spiral/clockwise direction; when ecountering the following elements replace them with the corresponding english statements: [X] or [] => Array X size of... or Array undefined size of... (type1, type2) => function passing type1 and type2 returning... * => pointer(s) to...
  2. Keep doing this in a spiral/clockwise direction until all tokens have been covered.
  3. Always resolve anything in parenthesis first!
               +---------+  
               | +-----+ |
               | | +-+ | |
               | | ^ | | |
           int * & t ; | |
            ^  ^ ^   | | |
            |  | +---+ | |
            |  +-------+ |
            +------------+

来自 t,所以:

t 是...

然后我们看到;,继续往前看&,所以

t 是对...

的引用

然后我们看到*

t 是指向...

的指针的引用

然后我们看到int:

t 是对指向 int

的指针的引用

这很有道理。现在让我们试试另一个:

               +---------+  
               | +-----+ |
               | | +-+ | |
               | | ^ | | |
           int & * t ; | |
            ^  ^ ^   | | |
            |  | +---+ | |
            |  +-------+ |
            +------------+

来自 t,所以:

t 是...

然后我们看到;,继续往前看*,所以

t 是指向...

的指针

然后我们看到&

t 是指向...

的引用的指针

到这里我们马上运行进入了一个问题。你不能有一个指向引用的指针。引用没有地址。

因为 int&* 没有真正意义,考虑符号的含义。

  • int: 一个数据类型
  • x *:指向数据类型x
  • 的指针
  • x &:引用数据类型x

我们可以将它们组合成以下常见的形式:

  • int *:指向 int
  • 的指针
  • int &: 对 int
  • 的引用

我会停下来说希望你知道 the difference between passing by reference and by pointer。如果没有,请参阅 link.

但是,我们可以尝试另一种组合:

  • int *&: 对指向 int 的指针的引用。

我们可以这样使用 int *&: 在来电者中:

int * myInt= 0;
myfunction(myInt);

在我的函数中(int *& myInt):

int i;
myInt = &i; 

调用者中的myInt int将是i的地址

NOTE: setting myInt to the address of a local variable is not a good idea, as the minute myFunction() ends, the data stored there will be destroyed. This is just for example purposes only

最后,还有问题:int&*

  • int &*:指向对 int
  • 的引用的指针

现在,我向你提出这个问题:如果我们有一个对 int 的引用,为什么我们需要一个指针?答:我们没有。没意义。

所以,简而言之:int*&int&* 是两个不同的东西。如果您将其分解,则第一个有意义,而第二个则没有。