函数、方法等中的const?

const本身是定义常量的,比如

const int buffSize = 512;

那么这个常量能否被一个整数指针引用呢,比如:
int *ptr = &buffSize;

由于编译器的局限性(不能跟踪程序在任意一点指向的对象,这个需要数据流分析),这个编译无法通过。那么这么办呢,就是定义一个常量指针:
const int *ptr;

常量可以常量指针引用,但是不能被修改。同时常量指针也可以指向变量,但是不能通过指针修改该变量:
ptr = &buffSize; //ok

int size = 16;
ptr = &size; //ok
*ptr = 17; // will cause an error

可以看出常量指针就是为const量身度作的。

现在转过来看这个函数定义:
int strcmp(const char* str1, const char* str2);
这里是什么意思呢?在实际的程序中,指向const的指针被当作形式参数,它作为一个约定来保证,被传递给函数的实际对象不会在程序中被修改。

最后,如果想定义一个完完全全的常量指针怎么做呢?如下:
const double PI = 3.14159265;
const double *const ptr = Π

 

一个相关参考程序:
/*************** begin of constPtr.cpp*******************/

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
 const double PI = 3.14158265;
 const double *ptr;

 ptr = &PI;

 cout << "The value of pointer /"ptr/" is " << *ptr << endl;

 double radius = 3.0;
 double area = PI * radius * radius;

 ptr = &area;

 cout << "The value of pointer /"ptr/" is " << *ptr << endl;
 

 /******* test const ptr***********/
 const double *const p2 = & PI;

 cout << "The value of p2 is " << *p2 << endl;

 /*
 p2 = &area;  // will cause an error here
 cout << "The value of p2 is " << *p2 << endl;
 */

 return 0;
}

/*************** endof constPtr.cpp*******************/
/***************build: g++ -o constPtr constPtr.cpp*******/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值