const和指针

1. 指针指向常量对象,可以防止使用该指针来修改所指向的值(可以将指针指向别的变量)

首先,声明一个指向常量的指针 pt:

int age = 39;

const int * pt = &age;

该声明指出,pt指向一个const int ,因此不能使用pt来修改这个值,也就是说*pt的值为const,不能够被修改

*pt += 1;  // invalid because pt pointers to a const int

cin >> *pt;  // invalid for the same reason

age = 20;  // valid bacause age is not declared to be const;

一般的用法:

const float g_earth = 9.80;  // g_earth为常量

const float *pe = &g_earth;  // pe为指向常量g_earth的指针

float *pm = &g_earth;  // invalid

c++禁止将const的地址赋值给非const指针,如果一定要这么做,可以通过强制类型转换来突破这种限制

如果指针指向指针,情况将变得更加复杂

一级指针时,将非const指针赋值给const指针时可以的

int age = 39;

int * pd = &age;

const int * pt = pd;

当涉及二级关系时,将const和非const混合的指针赋值方式将不再安全

const int **p2;

int *p1;

const int n = 29;

p2 = &p1;  // 不允许这样操作,假设可以这样

*p2 = &n;

p1 = 10;  // 改变了const n;

当且仅当只有一层间接关系时候,才可以将非const地址赋值给const指针

即:如果数据类型本身不是指针,可以将const类型数据和非const类型数据的地址赋值给const指针,但是只能将非const指针的地址赋值给非const指针

尽可能的使用const:

这样可以避免由于无意间修改数据导致的编程错误

使用const可以使函数处理const和非const实参,否则只能接收非const数据

2. 指针本身为常量,可以防止改变指针指向的位置(可以修改指针所指向的值)

int sloth = 3;

int * const finger = &sloth;

finger只能指向sloth,但是允许使用finger来修改sloth的值

如果愿意,还可以声明指向const对象的const指针

double trouble = 2;

const double * const stick = &trouble;

stick只能指向trouble,但是stick不能修改trouble的值。

原文地址:https://www.cnblogs.com/feng-ying/p/10509199.html