c******f 发帖数: 2144 | 1 a) int i = 37;
int &ref = i;
const int &cRef = ref;
i++;
printf("%d",cRef);
b) int i = 37;
int &ref = i;
const int &cRef = 30+ref;
i++;
printf("%d",cRef);
你觉得两个结果分别是多少?
38
67
谁能给解释下? |
s*********t 发帖数: 1663 | 2 第一个38
第二个如果能过编译的话就是67
【在 c******f 的大作中提到】 : a) int i = 37; : int &ref = i; : const int &cRef = ref; : i++; : printf("%d",cRef); : b) int i = 37; : int &ref = i; : const int &cRef = 30+ref; : i++; : printf("%d",cRef);
|
s*********t 发帖数: 1663 | 3 第一个:
const int &cRef = ref
cRef是一个可能为const 的int的引用,因此不能通过cRef修改其值
但是可以修改i或者通过ref修改i
第二个等价于const int &cRef = 67
【在 c******f 的大作中提到】 : a) int i = 37; : int &ref = i; : const int &cRef = ref; : i++; : printf("%d",cRef); : b) int i = 37; : int &ref = i; : const int &cRef = 30+ref; : i++; : printf("%d",cRef);
|
f****4 发帖数: 1359 | 4 为什么第二个是67而不是68?
const int &cRef = 30+ref;
ref在i++之后就是38了啊 |
r****o 发帖数: 1950 | 5 const?
【在 f****4 的大作中提到】 : 为什么第二个是67而不是68? : const int &cRef = 30+ref; : ref在i++之后就是38了啊
|
x***y 发帖数: 633 | 6 cRef should be reference of a temporary object, int(30+ref), which has
nothing to do with ref or i....But this causes problem, as the lifetime of
the object ends after the assignment...
【在 f****4 的大作中提到】 : 为什么第二个是67而不是68? : const int &cRef = 30+ref; : ref在i++之后就是38了啊
|
s*********t 发帖数: 1663 | 7 what is the significance of doing const int &xxx = 1234
?
【在 x***y 的大作中提到】 : cRef should be reference of a temporary object, int(30+ref), which has : nothing to do with ref or i....But this causes problem, as the lifetime of : the object ends after the assignment...
|
f****4 发帖数: 1359 | 8 you are right
cRef is referenced to a temporary object
【在 x***y 的大作中提到】 : cRef should be reference of a temporary object, int(30+ref), which has : nothing to do with ref or i....But this causes problem, as the lifetime of : the object ends after the assignment...
|
c******f 发帖数: 2144 | 9 This makes sense.
【在 x***y 的大作中提到】 : cRef should be reference of a temporary object, int(30+ref), which has : nothing to do with ref or i....But this causes problem, as the lifetime of : the object ends after the assignment...
|