有人可以向我解释什么是"reference reseating",为什么"a reference to point(refer) to another object"不可能?
Can somebody explain to me what is "reference reseating", and why is it not possible for "a reference to point(refer) to another object"?
根据这些链接:stackoverflow问题和C++FQA引用一旦初始化就不能很好地引用另一个对象/变量,但下面的代码呢?
// Example program in C++
#include <iostream>
using namespace std;
int main()
{
int x=10, z=12;
int &y=x;
++y;
y=z; //valid?
cout << x << ", "<< y <<", " << z << endl; // prints 12, 12, 12
return 0;
}
下面是关于指针重新定位的C代码,它似乎是有效的,对吗?
#include <stdio.h>
int main(int argc, char *argv[])
{
int a=10, b=20;
int *ptr;
ptr = &a;
ptr = &b;
printf("%dn",a); // prints 10
printf("%dn",*ptr); // prints 20
return 0;
}
有人能在以上两个代码中澄清上述概念吗?
y=z; //valid?
当然!但这并不意味着"y
从现在起就是z
"。意思是"将z
的值设置为y
当前所指的值",即x
。因此,y=z
是x=z
的另一种书写方式。
下面是关于指针重新定位的C代码,它似乎是有效的,对吗?
与引用不同,指针可以重新指向,因此指针的重新分配使其指向不同的变量。然而,您的程序并没有说明这一点,因为对ptr
的两个赋值在其间没有任何对ptr
的读取,所以只有第二个赋值保留下来。
在y=z
中
它不引用另一个变量,它只是将z
的值分配给y
,即12,并且由于y
引用了x
,所以x
也得到了分配的值12。
所以x=y=z=12
但在指针中,更改其指向的地址是有效的:
ptr = &a;
ptr = &b; //valid
相关文章:
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- Tensorflow c++ api undefined reference to 'tflite::D efaultErrorReporter()'
- 不断"Attempting to reference a deleted function"
- C++/SDL "initial value of reference to a non-const must be an lvalue"
- OpenCV undefined reference to 'cv::imread(cv::String const&, int)'
- Libcurl c++ "undefined reference to" (Windows/MinGW/g++)
- 尝试使用 extern "C" 调用 C 中的C++方法,得到"undefined reference to"对象的链接器错误
- 与映射和unordered_map相关的编译错误:"attempting to reference a deleted function"
- 将 QMutex 添加到类后的"Attempting to reference a deleted function"
- 多级继承错误 C2280:"atttempting to reference a deleted function"
- static_cast int to reference to int?
- C++:具有 const int 的类的 vector.erase 实例给出"attempting to reference a deleted function"错误 C2280
- "attempting to reference a deleted function"函数参数
- 错误 "Attempting to reference a deleted function" - 传回 unique_ptr 的值时
- 尝试使用 std::bind 重新分配 std::function 并得到错误"attempting to reference a deleted function"
- 我怎么知道"C2280 - attempting to reference a deleted function"发生在哪里?
- "Attempting to reference a deleted function"