英文:
Is redefinition of a pointer prohibited in c++ despite the pointer not being const?
问题
在我正在跟随的教程中提到,只要指针不是常量,就可以重新定义指针以包含不同变量的地址。但是以下代码块在重新定义指针时会出现错误(尽管指针不是常量类型)
#include <iostream>
int main() {
int int_data {33};
int other_int_data = 110;
int *p_int_data= &int_data;
//重新定义指针
int *p_int_data{&other_int_data};
//错误:重新定义 'p_int_data'
return 0;
}
当指针是常量时也会出现相同的错误。我想知道这是否是最新的更新,而在教程录制时还不存在这个问题。
英文:
In the tutorial that I am following, it is mentioned that pointers can be redefined to contain the addresses of a different variable, as long as the pointer is not constant. But the following block of code gives an error regarding redefinition of a pointer (even though the pointer is not of constant type)
#include <iostream>
int main() {
int int_data {33};
int other_int_data =110;
int *p_int_data= &int_data;
//redefining the pointer
int *p_int_data{&other_int_data};
//error : redefinition of 'p_int_data'
return 0;
}
The same error is there when the pointer is constant. I wonder if it is a latest update and was not at the time of recording of the tutorial.
答案1
得分: 2
一个变量除非进行遮蔽(在C++26中会有一个例外),否则无法重新定义。但是,您可以赋值给先前声明和定义的指针:
#include <iostream>
int main(){
int int_data {33};
int other_int_data = 110;
int *p_int_data = &int_data; // 声明和定义
p_int_data = &other_int_data; // 赋值,而不是声明或定义
return 0;
}
请注意,您不能使用花括号进行赋值,只能使用=
。
英文:
A variable can't be re-defined unless when shadowing (there will be an exception to this with C++26). You can, however, assign to the previously declared and defined pointer:
#include <iostream>
int main(){
int int_data {33};
int other_int_data = 110;
int *p_int_data = &int_data; // declaration and definition
p_int_data = &other_int_data; // assignment, not declaration or definition
return 0;
}
Note that you can't assign with curly braces, only with =
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论