【发布时间】:2019-02-01 05:32:35
【问题描述】:
为什么在 C++ 中,声明为数组的变量可以加或减整数,但不能递增(++)或递减(--)或乘数等,即使变量存储了起始地址大批? 例如
#include <iostream>
using namespace std;
int main()
{
int x[] = {12,33,41,55,68};
cout<<x<<"\n"; // Output : 0x7af786c84320
cout<<x+1<<"\n"; // Output : 0x7af786c84324
cout<<x+1000<<"\n"; // Output : 0x7af786c852c0
cout<<x-1000<<"\n"; // Output : 0x7af786c83380
cout<<x*1<<"\n"; /* Output : invalid operands of types
'int[5]' and 'int' to binary 'operator*' */
cout<<x*2<<"\n";
cout<<x++<<"\n"; /* Error : lvalue required as increment
operand */
cout<<x--<<"\n";
x=x; //Error : invalid array assignment
cout<<x<<"\n";
return 0;
}
如果有人能解释详细声明数组时会发生什么,那就更好了。 以及为什么在所有算术运算中只有'+'和'-'有效,'*'或其他无效。
【问题讨论】:
-
首先,
int x ={2,3,4,5,6};不编译。 -
int main{ int看起来像是语法错误。 -
不带 () 的 int main 也不编译。
-
抛开显示代码中的拼写错误,数组不能递增,因为 C++ 就是这样工作的。在 C++ 中,“增加一个数组”在逻辑上是没有意义的。那是什么意思“增加一个数组”。这种说法毫无意义。另一方面,如果您有一个指向数组的指针,您当然可以递增该指针。但是指针本身并不是数组。
标签: c++ c arrays pointers operators