【发布时间】:2018-07-26 14:00:30
【问题描述】:
代码如下:
int main()
{
int* p = nullptr;
const int* cp = p;
const int*& ref = cp;
const int*& ref0 = cp;
const int*& ref1 = p;//not allowed
const int*& ref2 = static_cast<const int*&>(p);//not allowed
int* const & ref3 = p;//allowed. Why?
return 0;
}
当我运行它时,我得到了
test.cpp:7:14: error: non-const lvalue reference to type 'const int *' cannot
bind to a value of unrelated type 'int *'
const int*& ref1 = p;
^ ~
test.cpp:8:21: error: non-const lvalue reference to type 'const int *' cannot
bind to a value of unrelated type 'int *'
const int*& ref2 = static_cast<const int*&>(p);
我很难理解为什么。也许const 在这里发挥了作用。而当我写const int*& 或int* const & 时,我不知道const 适用于指针或引用。 const int* const & 也让我感到困惑。
我想知道以下项目的语法:
对 const 指针的引用。
对指向 const 的指针的引用。
对一个 const 指针的引用并指向一个 const。
和 const 参考版本:
对指针的 const 引用。
对 const 指针的 const 引用。
对指向 const 的指针的 const 引用。
对一个 const 指针的 const 引用,该指针指向一个 const。
对不起,我的困惑。
【问题讨论】:
-
名为
ref的变量实际上并不是一个引用,它是一个指针。 -
@Eljay 抱歉输入错误。我已经更正了。
-
因为
const不具有传递性,所以这是两种不同的类型:const int*和int *。因此,当您将引用绑定到指针时,引用的类型必须与所引用事物的类型相匹配。根据您的最后一个示例,可以对非常量指针进行 const 指针引用。请记住,指针本身就是一个值,因为您似乎将指针视为值以外的东西。
标签: c++ pointers reference constants