gpt4 book ai didi

c++ - 问题 : 'const int * const & alias_for_ptr = ptr;' , 为什么两个标识符有不同的值?

转载 作者:太空狗 更新时间:2023-10-29 21:51:04 24 4
gpt4 key购买 nike

我无法理解 const int* const &alias_for_ptr = ptr; 的含义关于以下内容:

#include <iostream>
using namespace std;

int main() {

int a = 10;

int* ptr = &a;
const int* const &alias_for_ptr = ptr;

ptr = NULL; //or ptr = 0;

if (ptr == alias_for_ptr)
//This should execute but doesn't
cout << "ptr == alias_for_ptr" << endl;
else
//This should NOT execute but DOES
cout << "ptr != alias_for_ptr" << endl;
return 0;

}

为什么 ptr == alias_for_ptr 返回 false,(事实上 alias_for_ptr 保留其旧值 &a)?我的印象是 alias_for_ptr 将始终具有与 ptr 相同的值(尽管使用 & 符号)并且 const int* const X = Y 仅确保我不能同时更改 X 的值和 X 通过该标识符 X 指向的值。

此外,如果我删除第二个 const,那么脚本将无法编译,这让我更加困惑。请注意,编译错误是:invalid initialization of reference of type ‘const int*&’ from expression of type ‘int*’

最佳答案

您使用的是哪个编译器?我已经在 MSVC++ 2010 下编译,它如您所愿地工作。

我认为正在发生的事情是将一个临时变量分配给一个常量引用,因为“ptr”的类型从“int*”转换为“const int*”。如果删除第一个 const 会发生什么?

编辑:阅读此处了解更多引用资料:Reference initialization in C++ .

关于c++ - 问题 : 'const int * const & alias_for_ptr = ptr;' , 为什么两个标识符有不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4482242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com