我是靠谱客的博主 安静飞鸟,这篇文章主要介绍常量指针、指向常量的指针、指向常量的常量指针一、常量指针二、指向常量的指针三、指向常量的常量指针,现在分享给大家,希望可以做个参考。

目录

一、常量指针

二、指向常量的指针

三、指向常量的常量指针


一、常量指针

指针是一个常量,不能改变指向,常量指针必须初始化。

#include<iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
int * const p
= &b;
p = &a; //	[Error] assignment of read-only variable 'p'
cout<<*p<<endl;
return 0;
} 

 

二、指向常量的指针

不能通过该指针改变指向的值,但可以改变指向,也不要以为该指针只能指向常量,也可以指向非常量,这里的指向常量其实是无法改变指向的值。不要被指向常量四个字所限制。

#include<iostream>
using namespace std;
int main()
{
const int one = 10;
int two = 200;
const int *p = &one; //指向常量的指针
cout<<*p<<endl;
*p = 20;
//	不可以改变指向的值 [Error] assignment of read-only location '* p'
p = &two; //
可以改变指向
return 0;
} 

三、指向常量的常量指针

指针的指向和指向的值均不能改变

#include<iostream>
using namespace std;
int main()
{
const int one = 10;
int two = 200;
const int *const p = &one; //指向常量的常量指针
cout<<*p<<endl;
*p = 20;
// [Error] assignment of read-only location '*(const int*)p'
p = &two; // [Error] assignment of read-only variable 'p'
return 0;
} 

 

最后

以上就是安静飞鸟最近收集整理的关于常量指针、指向常量的指针、指向常量的常量指针一、常量指针二、指向常量的指针三、指向常量的常量指针的全部内容,更多相关常量指针、指向常量内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(112)

评论列表共有 0 条评论

立即
投稿
返回
顶部