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



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

#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;
}

我很困惑这段代码是如何运行的,因为它们给了我一个4 4的结果,不应该像5 5吗?因为它被c和d加了两次?我已经掌握了decltype的窍门,但这项任务让我再次困惑于代码是如何工作的。

decltype(a) c = a;变为int c = a;,因此c是值为3a的副本。

CCD_ 9变为CCD_ 10,因为CCD_ 12中的CCD_。

因此,我们将c作为一个值为3的独立变量,而d是指a也具有值3。当您同时递增cd时,这两个3秒都变为4秒,这就是为什么您将4 4作为输出

此代码可以重写为:

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;

ca的不同拷贝,将其增加1得到4

da的引用(但仍然与c无关(,将其递增也会得到4(唯一的区别是a也被修改,因为ad都指同一个变量(。

最新更新