问题描述
我是C ++的初学者,对于指针的用途存在以下问题,其中指针的地址或值都无法更改( constEverything
示例)。
I am a beginner to C++ and have the following question regarding the purpose of pointers where neither the address nor the value that it is pointing to can be changed (constEverything
in the example).
示例:
int main()
{
int i = 1;
int j = 2;
int* const constPoint = &i;
*constPoint = 3; // legal
constPoint = &j; // illegal
const int* constVal = &i;
*constVal = 3; // illegal
constVal = &j; // legal
const int* const constEverything = &i;
*constEverything = 3; // illegal
constEverything = &j; // illegal
}
在示例中,指针的类型。使用 constVal
您可以更改地址,使用 constPoint
您可以更改基础值。对于 constEverything
,您将无法执行任何操作。
In the example there are different types of pointers. With constVal
you can change the address and with constPoint
you can change the underlying value. For constEverything
you can do neither.
对我来说,这种指针的目的是通过常量引用传递事物。为什么我不应该只使用 const type& val ?对我来说,const引用似乎容易得多,它使 const type * const val 过时。
To me the purpose of such a pointer would be to pass things by constant reference. Why should I not just use const type &val instead? To me a const reference seems a lot easier and it makes const type* const val obsolete.
推荐答案
常量指针很有用,主要有两个原因。
Constant pointers are useful for two principal reasons.
-
this
是const const
指针/ code>成员函数。
this
is aconst
pointer in aconst
member function.
A const
指针也可以设置为 nullptr
。
A const
pointer can also be set to nullptr
.
我的第一个观点有点循环,此
可以是引用类型或 const
引用类型,但是引用迟到了C ++标准,并且所有更改都将被取消。
My first point is somewhat circular, this
could have been a reference type or a const
reference type, but references arrived late into the C++ standard, and any changes would have been breaking.
这篇关于C ++中的常量指针的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!