首页 > 解决方案 > c ++中常量指针的目的是什么?

问题描述

我是 C++ 的初学者,并且有以下关于指针的用途的问题,其中地址和它指向的值都不能更改(constEverything示例中)。

例子:

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你什么都做不了。

对我来说,这样一个指针的目的是通过常量引用传递事物。为什么我不应该只使用const type &val来代替?对我来说,一个 const 引用似乎要容易得多,它使const type* const val过时了。

标签: c++pointersreferenceconstants

解决方案


常量指针之所以有用,主要有两个原因。

  1. this是成员函数const中的指针。const

  2. const指针也可以设置为nullptr

我的第一点有点循环,this 可能是引用类型或const引用类型,但引用在 C++ 标准中出现较晚,任何更改都会中断。


推荐阅读