C++const关键字和指针的结合使用

#include<iostream>

using namespace std;

/**
 * C++const关键字和指针的结合使用
 * 1,指针常量:可以修改指针变量指向地址的值,不能修改指针变量的指向(即可以给*p赋值, 不能给p赋值)
 * 语法: dataType *const pointerVariableName = &variableName;
 * 2,常量的指针:不可以修改指针变量指向地址的值,能修改指针变量的指向(即可以给p赋值, 不能给*p赋值)
 * 语法: const dataType *pointerVariableName = &variableName;
 * 3,指向常量的指针常量:不可以修改指针变量指向地址的值,也不能修改指针变量的指向(即不可以给p赋值, 不能给*p赋值)
 * 语法: const dataType *const pointerVariableName = &variableName;
 */
int main() {
    int a = 10;
    int b = 20;
    //pointer constant
    int *const constP = &a;
    cout << "Before assignment again for value of variable which is pointed at pointer constant constP is " << *constP
         << endl;
    *constP = 100;
    cout << "After assignment again for value of variable which is pointed at pointer constant constP is " << *constP
         << endl;
    //constP = &b;
    //error: assignment of read-only variable 'constP'

    //constant's pointer
    const int *poc = &b;
    cout
            << "Before assignment again for constant's pointer poc, the value of constant which is point at constant's pointer is "
            << *poc << endl;
    poc = &a;
    cout
            << "After assignment again for constant's pointer poc, the value of constant which is point at constant's pointer is "
            << *poc << endl;
    //*poc = 100;
    //error: assignment of read-only location '* poc'

    //pointer constant's pointer
    const int *const constPoc = &b;
    //constPoc = &a;
    //error: assignment of read-only variable 'constPoc'
    //*constPoc = 100;
    //error: assignment of read-only location '*(const int*)constPoc'
    system("pause");

    return 0;
}

如何理解和记忆/区分指针常量常量的指针?

看const关键字修饰的是什么

形如:int *const p = &a;明显const修饰的是变量p,变量p是什么变量呢?

指针变量,即指针变量的值不能修改,而指针变量的值是地址,不能改变地址即不能改变指针变量的指向,即该指针变量是常量,故称为指针常量

形如:const int *p = &a;明显const修饰的变量*p,变量*p是什么变量呢?

指向整型变量的指针p指向的变量,即一个整型变量,整型变量*p不能被修改即不能改变整型变量*p的值,即整型变量*p是个常量,故指针p被称为指向常量的指针

posted @ 2020-08-08 12:24  DNoSay  阅读(221)  评论(0编辑  收藏  举报