我是编程新手,有人能向我解释一下这段代码是如何工作的吗?
#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
是值为3
的a
的副本。
CCD_ 9变为CCD_ 10,因为CCD_ 12中的CCD_。
因此,我们将c
作为一个值为3
的独立变量,而d
是指a
也具有值3
。当您同时递增c
和d
时,这两个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;
c
是a
的不同拷贝,将其增加1
得到4
。
d
是a
的引用(但仍然与c
无关(,将其递增也会得到4
(唯一的区别是a
也被修改,因为a
和d
都指同一个变量(。