C++ 常量指针、指向常量的指针和指向常量的常量指针之间的区别

C++ 常量指针、指向常量的指针和指向常量的常量指针之间的区别

在本文中,我们将讨论 常量指针 、指向常量的指针和指向常量的常量指针之间的区别。指针是保存其他变量、常量或函数的地址的变量。使用 const 可以对指针进行多种限定。

  • 指向常量的指针。
  • 常量指针。
  • 指向常量的常量指针。

指向常量的指针:

在指向常量的指针中,指针所指向的数据是常量,无法更改。但是,指针本身可以更改,并指向其他位置(因为指针本身是一个变量)。

下面是说明这点的示例程序:

// C++ program to illustrate concept
// of the pointers to constant
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
 
    int high{ 100 };
    int low{ 66 };
    const int* score{ &high };
 
    // Pointer variables are read from
    // the right to left
    cout << *score << "\n";
 
    // Score is a pointer to integer
    // which is constant *score = 78
 
    // 将导致错误:
    // 试图将常量赋值为新值
    // assignment of read-only location
    // ‘*score’
    score = &low;
 
    // 在这里可以这样做,因为我们
    // 改变了score指向的位置,现在它指向low。
    cout << *score << "\n";
 
    return 0;
}  

输出:

100
66

常量指针:

在常量指针中,指针指向一个固定的内存位置,该位置的值可以更改,因为它是一个变量,但指针始终会指向相同的位置,因为这里做了一个常量处理。

下面的示例是为了了解常量指针与引用的关系。引用可以被认为是自动解引用的常量指针。传递的实际参数的值可以被更改,但引用指向相同的变量。

C++ 常量指针、指向常量的指针和指向常量的常量指针之间的区别

下面是说明这点的示例程序:

// C++ program to illustrate concept
// of the constant pointers
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
 
    int a{ 90 };
    int b{ 50 };
 
    int* const ptr{ &a };
    cout << *ptr << "\n";
    cout << ptr << "\n";
 
    // 显示它指向什么地址
 
    *ptr = 56;
 
    // 可以接受改变a的值
 
    // 会导致错误:试图将常量赋值为新值
    // ptr = &b
 
    cout << *ptr << "\n";
    cout << ptr << "\n";

    return 0;
}  

输出:

90
0x7ffc641845a8
56
0x7ffc641845a8

指向常量的常量指针:

在指向常量的常量指针中,指针所指向的是常量数据,无法更改。指针本身也是常量,不能更改指向位置。下面的图像说明这一点:

C++ 常量指针、指向常量的指针和指向常量的常量指针之间的区别

下面的程序说明这一点:

// C++程序演示常量指针的概念
// const
#include <iostream>
using namespace std;
 
// 驱动程序
int main()
{
 
    const int a{ 50 };
    const int b{ 90 };
 
    // 指针指向a
    const int* const ptr{ &a };
 
    // *ptr = 90;
    // 错误:只读位置的赋值
    // ’*(const int*)ptr’
 
    // ptr = &b;
    // 错误:只读变量的赋值
    // ‘ptr’
 
    // a的地址
    cout << ptr << "\n";
 
    // a的值
    cout << *ptr << "\n";
 
    return 0;
}  

输出:

0x7ffea7e22d68
50

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程