C++ 运算符优先级表



++ 和 * 混合运用简单测试

int arr[5] = { 10, 20, 30, 40, 50 };
int *p1 = arr;
int res_p1 = ++ * p1;
cout << "++*p1 = " << res_p1 << '\n';    // 11 先解引用,然后对解引用后的值做++, arr[0] = 11
cout << "*p1 = " << *p1 << '\n';         // 11 p1 的指针没有动,还是指向 arr[0] = 11

int res_p1_2 = *++p1;                    // 先对指针进行++操作,然后再解引用,相当于arr[1]的值
cout << "*++p1 = " << res_p1_2 << '\n';  // 20
cout << "*p1 = " << *p1 << '\n';         // 20 指针已经++,指向了 arr[1]=20

cout << '\n';

int arr1[5] = { 100, 200, 300, 400, 500 };
int *p2 = arr1;
int res_p2 = *p2++;                      // res_p2 = 100, 指针指向 arr1[1],指针做了++运算
cout << "res_p2 = " << res_p2 << '\n';   // 100
cout << "*p2 =" << *p2 << '\n';          // 200   指针做了 ++ 操作

输出:

++*p1 = 11
*p1 = 11
*++p1 = 20
*p1 = 20

res_p2 = 100
*p2 =200

*(解引用)和++(前置或后置)都是右结合律的。




《C++ Primer》 P148
posted @ 2024-10-16 15:26  double64  阅读(58)  评论(0)    收藏  举报