简体   繁体   English

为什么对数组的const左值引用不能在下面编译?

[英]Why doesn't the const lvalue reference to an array compile below?

The const lvalue reference int(const& crb)[3] = b; 常量左值引用int(const& crb)[3] = b; doesn't compile. 无法编译。 Why? 为什么?

#include<iostream>

int a = 1;
int b[3] = { 1, 2, 3 };

int main(){
    int& ra = a;             // Ok
    int const& cra = a;      // Ok

    int(&rb)[3] = b;         // Ok
    int(const& crb)[3] = b;   // Doesn't compile
}

Error message emitted by g++: g ++发出的错误消息:

error: expected primary-expression before 'int'
int(const& crb)[3] = b;
^~~

Reference is always constant, you can't change reference. 参考始终是恒定的,您不能更改参考。 int const (& crb)[3] = b; here we have reference to array of const int, we can also write const int (& crb)[3] = b; 这里我们引用了const int数组,我们也可以写const int (& crb)[3] = b; It would be the same. 会是一样的。

Pointers have a difference, pointer can be changed 指针有所不同,可以更改指针

const int *p; - here it is pointer on const int -这是const int的指针

int const *p; - here it is const pointer on int -这是int上的const指针

const int const *p; - here it is const pointer on const int -这是const int上的const指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么const double &amp;&amp;不适用于左值引用? - Why const double && doesn't work for lvalue reference? const_cast转换为左值引用不会删除constness - const_cast conversion to lvalue reference doesn't remove constness 为什么通过const引用传递constexpr对象有效,但是按值不能编译 - Why passing constexpr object by const reference works, but by value doesn't compile 在C ++标准中哪里说明const rvalue引用未绑定到lvalue? - Where in the C++ Standard is it stated that a const rvalue reference doesn't bind to an lvalue? 为什么不能将const左值引用绑定到返回T &amp;&amp;的函数? - Why can't I bind a const lvalue reference to a function returning T&&? 错误:非常量左值引用 w.r.t。 boost::multi_array 和 foreach - error: non-const lvalue reference w.r.t. boost::multi_array and foreach 通过引用传递*使用const成员函数的this不能编译? - Pass By Reference Using *this from const member function doesn't compile? 为什么左值引用不能绑定到 const const“转发引用”? - Why can't lvalue references bind to const const "forwarding references"? 为什么const / nonconst左值引用都绑定到右值引用? - Why both const/nonconst lvalue references bind to a rvalue reference? 为什么非常量引用必须用左值初始化? - Why must a non-const reference be initialized with an lvalue?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM