指针:初始化与声明

最大

我是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;
}

但是为什么这也起作用?

#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;
}
丹尼尔·戴

这两行之间的根本区别

*test= &a; // 1
int a, *test= &a; // 2

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

       operator=
          /\
        /    \
      /        \
operator*    operator&
  |             | 
 test           a

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

   int*     test    =  &a
// ^^        ^^        ^^
//type    variable    expression giving
//          name        initial value

既不operator*也不operator=在第二行甚至使用。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章