繁体   English   中英

将引用绑定到指针的语法是什么?(所有类型)

[英]what's the syntax to bind reference to pointer?(all kinds)

这是代码:

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引用。

对不起,我很困惑。

您的p是一个指向int的指针。 const int*&是对指向const int的指针的引用。 由于pint而不是const int ,因此您不能将应该引用指向const int的指针的引用绑定为引用p

在C ++中读取声明的关键是“从内而外”读取它们,即从标识符(名称)开始,然后逐步退出。 举个例子:

int* const & ref3;

是对指向intconst指针的引用。 我们从标识符( ref3 )开始,然后向外进行。 我们发现的第一件事是& 因此, ref3是一个参考。 接下来是const ,因此ref3引用的都是const 下一个是* ,因此引用引用的const是指针。 最后是int ,我们正在处理对指向intconst指针的引用。

请注意,标识符的两面都可能发生一些事情。 “解决问题”时,您必须考虑首先/更强地绑定哪些说明符/运算符,以找出声明的类型。 例如:

int const * a[10];

同样,我们从标识符a开始。 []绑定比*更牢固,因此a是10个元素的数组。 a是数组的这些元素是什么? 接下来是* ,因此a是由10个指针组成的数组。 最后,我们发现a是10个指向const int指针的数组。 请注意,如果最后还有一个孤独的const ,则该const绑定到它之前的任何内容。 那就是允许我们也写const int a ,它等效于int const a

您还可以使用括号来影响运算符在声明中生效的顺序。 例如

int const (* a)[10];

将是指向10 const int数组的指针,而不是指向const int的10指针的数组。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM