与C+&#x2B中指针的引用相混淆。
任务是在没有计算机的情况下计算以下源代码的输出,我想说的是 "123 234 678 678"
因为 ref1
是对值的引用ptr
并且在将 val2
的地址分配给该指针的那一刻,那么 ref1
不应该引用它的值吗?
int main() {
int* ptr = nullptr;
int val1 = 123, val2 {234};
ptr = &val1;
int& ref1 = *ptr;
int& ref2 = val2;
std::cout << ref1 << " ";
std::cout << ref2 << " ";
*ptr = 456; //ref1 = 456
ptr = &val2; //*ptr = 234, why isn't ref1 as well equal to 234?
*ptr = 678; //*ptr = 678, why isn't ref1 as well equal to 678?
std::cout << ref1 << " ";
std::cout << ref2 << "\n";
return EXIT_SUCCESS;
//output: 123 234 456 678
}
The task is to calculate the output of the following source code without a computer, which I would say is "123 234 678 678"
because ref1
is a reference on the value of ptr
and in the moment where the address of val2
is assigned to this pointer, then shouldn't ref1
as well refer to its value?
int main() {
int* ptr = nullptr;
int val1 = 123, val2 {234};
ptr = &val1;
int& ref1 = *ptr;
int& ref2 = val2;
std::cout << ref1 << " ";
std::cout << ref2 << " ";
*ptr = 456; //ref1 = 456
ptr = &val2; //*ptr = 234, why isn't ref1 as well equal to 234?
*ptr = 678; //*ptr = 678, why isn't ref1 as well equal to 678?
std::cout << ref1 << " ";
std::cout << ref2 << "\n";
return EXIT_SUCCESS;
//output: 123 234 456 678
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在此声明之后,
ref1
引用val1
,ref2
引用val2
。声明后,不能将引用更改为引用其他变量。请注意,引用
ref1
并不引用指针ptr
。由于取消引用指向变量val1
的指针,它引用了变量val1
。所以这些语句
将输出
In this statements
the value of the value of the variable
val1
ischanged to456
through using thepointerptr
.之后指针
ptr
的值被更改为存储变量val2
的地址,并且变量
val2
的值更改为< code>678 通过使用指针所以这些语句
现在将输出
即它们输出引用所引用的变量的值。
在此程序中,由于使用对象地址重新分配了指针,因此使用同一个指针来更改两个不同对象的值。
After this declarations
ref1
refers toval1
andref2
refers toval2
. After the declarations the references can not be changed to refer to other variables.Pay attention to that the reference
ref1
does not refer to the pointerptr
. It refers the variableval1
due to dereferencing the pointer that points to the variableval1
.So these statements
will output
In this statement
the value of the variable
val1
is changed to456
through using the pointerptr
.After that the value of the pointer
ptr
was changed to store the address of the variableval2
and the value of the variable
val2
was changed to678
through using the pointerSo these statements
now will output
That is they output values of the variables to which the references refer to.
In this program the same one pointer was used to change values of two different objects due to reassignment of the pointer with addresses of the objects.