为什么在 cpp/c 中使用指针引用时增量运算符 (++) 不起作用

-5 c++ increment c++14

我正在编写与 C/C++ 中的引用相关的代码。我创建了一个指针并将其放入一个递增它的函数中。在函数中,我编写*ptr++并尝试增加指针指向的整数的值。

#include <iostream>
using namespace std;

void increment(int *ptr)
{
    int &ref = *ptr;
    *ptr++; // gets ignored?
    ref++;
}

int main()
{
    int a = 5;
    increment(&a);
    cout << a;

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

谁能告诉我为什么我不能增加变量?我尝试使用 来增加它+=1,它可以工作,但不能通过使用++运算符?

Bar*_*mar 6

++优先级高于*,因此*ptr++被视为*(ptr++)。这会增加指针,而不是它指向的数字。

要增加数字,请使用(*ptr)++