指针:初始化与声明

max*_*axE 17 c++ pointers c++14

我是一个C++菜鸟,我很确定这是一个愚蠢的问题,但我不太明白为什么从以下代码出现错误(不会出现):

#include <iostream>
using namespace std;


int main() 
{
int a,*test; 

*test = &a;  // this error is clear to me, since an address cannot be 
             // asigned to an integer  


*(test = &a); // this works, which is also clear
return 0;
}
Run Code Online (Sandbox Code Playgroud)

但为什么这也有效呢?

#include <iostream>
using namespace std;

int main() 
{
int a, *test= &a;  // Why no error here?, is this to be read as:
                   // *(test=&a),too? If this is the case, why is the 
                   // priority of * here lower than in the code above?

return 0;
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*our 30

这两条线之间的根本区别

*test= &a; // 1
int a, *test= &a; // 2
Run Code Online (Sandbox Code Playgroud)

是第一个是一个表达式,由具有已知优先级规则的运算符调用组成:

       operator=
          /\
        /    \
      /        \
operator*    operator&
  |             | 
 test           a
Run Code Online (Sandbox Code Playgroud)

而第二个是变量声明和初始化,相当于int a;后面的声明:

   int*     test    =  &a
// ^^        ^^        ^^
//type    variable    expression giving
//          name        initial value
Run Code Online (Sandbox Code Playgroud)

在第二行中既不使用operator*也不operator=使用.

标记*=(&以及,)的含义取决于它们出现的上下文:表达式中它们代表相应的运算符,但在声明中*通常表现为类型的一部分(意思是"指向") )并=用于标记(复制)初始化表达式的开头(,分隔多个声明,&因为"引用"也是该类型的一部分).