为什么原始值没有增加两次,即使我有两次增量

Mak*_*aki 8 c++ reference increment decltype

我是编程新手,有人可以向我解释这段代码是如何工作的吗?

#include <iostream>
using namespace std;

int main () {

    int a = 3, b = 4;
    decltype(a) c = a;
    decltype((b)) d = a;
    ++c;
    ++d;


    cout << c << " " << d << endl;
}
Run Code Online (Sandbox Code Playgroud)

我很困惑这段代码是如何运行的,因为它们给了我一个结果4 4,不应该是这样吗5 5?因为它被 c 和 d 增加了两倍?我正在掌握窍门decltype,但这项作业让我对代码如何再次工作感到困惑。

Nat*_*ica 18

decltype(a) c = a;值为 的副本变为int c = a;如此。ca3

decltype((b)) d = a;变成int& d = a;因为(expr)in adecltype将推导出对表达式类型的引用。

因此,我们有c一个值为 的独立变量3d它指的a是它的值为3。当你增加两个c并且d这两个3s 都变成4s 时,这就是为什么你得到4 4输出


Far*_*nor 8

这段代码可以重写为:

int a = 3;  //Forget about b, it is unused

int c = a;  // copy (c is distinct from a)
int& d = a; // reference (a and d both refers to the same variable)

++c;
++d;
Run Code Online (Sandbox Code Playgroud)

c是 的一个不同副本a,将其递增14

d是 的引用a(但仍然与 无关c),递增它也给出4(唯一的区别是a也被修改,因为a两者d都引用相同的变量)。