运算符++应该等效于+ 1,那么为什么下面的示例产生不同的结果?

#include <iostream>
#include <string>

int main()
{
    int i, n=25;
    std::string s1="a", s2="a", s1p="", s2p="";

    for (i=0;i<=n;i++)
    {
        s1p += s1;
        s1 = s1.at(0) + 1;

        s2p += s2;
        s2 = s2.at(0)++;
    }
    std::cout << "s1p = " << s1p << "\n" << "s2p = " << s2p << "\n";

    return 0;
}

Ouput:
s1p = abcdefghijklmnopqrstuvwxyz
s2p = aaaaaaaaaaaaaaaaaaaaaaaaaa

最佳答案

后增量返回变量先前保留的值。

x++(后递增)视为

int y = x;
x = x+1;
return y;


++x(预递增)为

x = x+1;
return x;


为了获得理想的结果,您需要预先增加。

10-05 21:29