const int const&和const int&in C++有什么区别?

Whats the difference between const int const& and const int& in C++?

本文关键字:const int 区别 什么 in C++      更新时间:2023-10-16

在C 中,我可以为常量指针编写const int const*。我也可以为const引用编写const int&const int const&是对const int的引用?

预先感谢!

const int const*不是恒定的指针到常数int。为了获得您需要

const int * const.

在您的情况下,您将两个const都应用于int,因此您有一个可变的指针到常量的int

const int const&也发生了同样的事情。为了持续参考常数int,您需要

const int & const

但这是非法的。

请注意,在const int const*const int const&中,两次应用const实际上不是合法的。

const int const&对const int的引用?

不,这是一个汇编错误。

尝试编译以下内容:

int z = 0;
const int const& a= z;

,您会看到编译器会向您大喊大叫。

您无法重复相同类型的const。您的前提是const int const*是常数指向常数int也是错误的。

如果您陷入了理解此类声明时,最好像顺时针/螺旋规则那样向后阅读它。

int const *    // pointer to const int
int * const    // const pointer to int
int const * const   // const pointer to const int
int * const * p3;   // pointer to const pointer to int
const int * const * p4;       // pointer to const pointer to const int