C++中是否禁止重新定义指针,尽管指针不是const?

huangapple go评论67阅读模式
英文:

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 &lt;iostream&gt;

int main() {
    int int_data {33};
    int other_int_data =110;
    
    int *p_int_data= &amp;int_data;
    //redefining the pointer
    int *p_int_data{&amp;other_int_data};
    //error : redefinition of &#39;p_int_data&#39; 
    
    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 &lt;iostream&gt;

int main(){
    int int_data {33};
    int other_int_data = 110;

    int *p_int_data = &amp;int_data;  // declaration and definition
    p_int_data = &amp;other_int_data; // assignment, not declaration or definition

    return 0;
}

Note that you can't assign with curly braces, only with =.

huangapple
  • 本文由 发表于 2023年7月10日 13:32:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76650868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定