#include <iostream>
using namespace std;
int main()
{
// 可以将const指针赋给const指针,但b不能把const指针赋给常规指针
const float g_earth = 9.80;
const float *pe = &g_earth;
// float *pm = &g_earth; 错误
// 一级间接关系
int zz = 30;
int *pd = &zz; // *pd = 41 正确
const int *pt1 = pd; //*pt1 = 41 错误
// 两级间接关系
const int **pp2;
int *p1;
const int n=13;
// pp2 = &p1 //不允许,但支持这么做
// *pp2 = &n; // 会让p1指向n
// *p1 = 10; // 有效,但改变了const n
// cout<<*pp2<<*p1<<n;
int age = 39;
const int *pt = &age; // pt指向const int,*pt的值不能修改,但pt本身的值可以修改
age = 20; // 因为age不是const,因此可以修改age的值,此时*pt的值也会改变
int sage = 80;
pt = &sage; // pt指向sage,*pt的值为80
cout<<"*pt:"<<*pt<<" "<<"age:"<<age<<endl;
int sloth = 3;
// 指针常量, 指向const int, 不能通过ps来修改sloth的值,但允许将ps指向令一个位置
const int *ps = &sloth;
ps = &age;
//常量指针,指向int, 无法修改指针本身的值,只能指向sloth,但可以使用*finger修改sloth的值
int *const finger = &sloth;
*finger = 5;
cout<<"sloth:"<<sloth<<endl;
// const对象的const指针,stick只能指向sloth且*stick的值不能修改
const int *const stick = &sloth;
}
c++ const和指针代码说明
最新推荐文章于 2023-04-06 09:50:39 发布