【发布时间】:2017-11-20 00:19:13
【问题描述】:
我是一个 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;
}
【问题讨论】:
-
int *x = y;表示y是x的初始化器(不是*x)。也不是赋值表达式 -
@M.M 好吧,我必须阅读 int *test = &a as int *(test = &a) ?
-
不,读作声明了一个名为
test的变量,类型为int *,初始化程序为&a。 -
*=&在声明中的含义与在表达式中的含义不同 -
如您所见,最好避免在一行上声明多个变量。