博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
const 指针的三种使用方式
阅读量:4325 次
发布时间:2019-06-06

本文共 1560 字,大约阅读时间需要 5 分钟。

///const 指针的三种状态/

注意:const 的前后顺序

const 在类型之前 ---可以修改指针包含的地址,不能修改指针指向的值
const 在变量之前类型之后 ---可以修改指针的指向值,不能修改指针地址

 

 

// 1.指针指向的数据为常量,不能修改,但是可以修改指针包含的地址

/*

int HoursInDay = 24;
const int* pInteger = &HoursInDay;

cout<<HoursInDay<<" "<<*pInteger<<endl;

//*pInteger = 55; //不能通过指针修改指向的值

cout<<HoursInDay<<" "<<*pInteger<<endl;

int MonthsInYear = 12;

pInteger = &MonthsInYear; //可以修改指针指向的地址

//*pInteger = 13;

//int *pAnotherPointerToInt = pInteger; //指针的类型不同不能用于拷贝

*/

//2.指针包含的地址是常量,不能修改,但可以修改指针指向的数据

/*

int DaysInMonth = 30;
int* const pDaysInMonth = &DaysInMonth;

*pDaysInMonth = 31; //Ok! value can be change

int DaysInLunarMonth = 28;

//pDaysInMonth = &DaysInLunarMonth; Cannot change address!
*/

//3.指针包含的地址以及它指向值都是常量,不能修改(这种组合最为严格)

/*

int HoursInDay = 24;

const int* const pHoursInDay = &HoursInDay;

//*pHoursInDay = 25; cannot change pointed value 不能修改指向的值

int DayInMonth = 30;

//pHoursInDay = &DayInMonth; cannot change pointer value 不能修改指针

*/

 

将指针传递给函数时,这些形式的const很有用。函数参数应声明为最严格的const指针,以确保函数不会修改指针指向的值。这让函数更容易维护,在时过境迁和人员更换尤其如此。

 

 

void CalcArea(const double* const pPi,        //const pointer to const data

                    const double* const pRadius, //i.e.. nothing can be changed
                    double* const pArea              //change pointed value,not address
                   )
{
       //check pointers before using!
       if (pPi && pRadius &&pArea)
      {
          *pArea = (*pPi) * (*pRadius) *(*pRadius);
      }
}

int main()
{
const double PI = 3.14;

cout << "Enter radius of circle: ";

double Radius = 0;
cin >> Radius;

double Area = 0;

CalcArea(&PI,&Radius,&Area);

cout << "Area is = "<<Area<<endl;

}

 

 

 

转载于:https://www.cnblogs.com/cci8go/p/3798986.html

你可能感兴趣的文章
[CF193B] Xor(暴力,剪枝,异或)
查看>>
[CF825D] Suitable Replacement (贪心乱搞)
查看>>
大数据笔记(二十五)——Scala函数式编程
查看>>
win7 IIS7 运行vs2003 web 项目 无法识别的配置节“system.webServer” 解决
查看>>
jQuery源码分析_工具方法(学习笔记)
查看>>
有穷自动机的转换
查看>>
ncbi-blast 本地安装
查看>>
在android上使用 stand-alone toolchains移植 transmission
查看>>
小议IT公司的组织架构
查看>>
在Eclipse中编写jQuery代码时产生的错误(连载)
查看>>
java 中 this的使用
查看>>
多线程和蕃茄炒蛋
查看>>
SSH错误:packet_write_wait: Connection to 10.57.19.250 port 22: Broken pipe
查看>>
ACTION 关联表之间查询语句 SQL语句写法
查看>>
find命令
查看>>
Ambari——大数据平台的搭建利器之进阶篇
查看>>
模块内高内聚?模块间低耦合?MVC+EF演示给你看!
查看>>
ACM学习心得及书籍推荐
查看>>
springcloud
查看>>
Binary Tree Inorder Traversal
查看>>