[英]Whats the difference between const int const& and const int& in C++?
In c++ i can write const int const*
for a constant pointer to an constant int. 在c ++中,我可以编写const int const*
来获取指向常量int的常量指针。 I can also write const int&
for a const reference. 我也可以编写const int&
for const reference。 So is const int const&
a reference to a const int? 那么const int const&
对const int的引用吗?
Thanks in advance! 提前致谢!
const int const*
is not a constant pointer to a constant int
. const int const*
不是指向常量int
的常量指针。 To get that you need 为了得到你需要的
const int * const.
In your case you apply both const
to the int
so you have a mutable pointer to a constant int
. 在您的情况下,您将两个const
应用于int
因此您有一个指向常量int
的可变指针。
The same thing happen to const int const&
. const int const&
发生了同样的事情。 To make a constant reference to a constant int
you would need 要对常量int
进行常量引用,您需要
const int & const
but that is illegal. 但那是违法的。
Do note that in both const int const*
and const int const&
it's not actually legal to apply const
twice like that. 请注意,在const int const*
和const int const&
,使用const
两次实际上并不合法。
So is const int const& a reference to a const int? 那么const int const和对const int的引用吗?
No, that's a compilation error . 不,那是编译错误 。
Try compiling something like : 尝试编译类似的东西:
int z = 0;
const int const& a= z;
And you'll see the compiler will yell at you. 你会看到编译器会对你大喊大叫。
You can't duplicate const
for the same type. 您不能复制相同类型的const
。 Your premise that const int const*
is a constant pointer to a constant int
is wrong too. const int const*
是一个指向常量int
的常量指针的前提也是错误的。
It is always a good idea to read it backwards as suggested by the Clockwise/Spiral rule if you get stuck in understanding such declarations. 如果您不理解这样的声明,那么按顺时针/螺旋规则的建议向后阅读它总是一个好主意。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.