函数、方法等中的const?
来源:互联网 发布:东北黑帮网络大电影 编辑:程序博客网 时间:2024/05/01 16:36
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*******/
- 函数、方法等中的const?
- 18、函数参数中的const
- const在函数中的作用
- C++中的const成员函数
- c++中的const 成员函数
- c++ 中的const 成员函数
- C++中的const成员函数
- 类中的const成员函数
- C++中的const成员函数
- c++中的const成员函数
- 虚函数知识点,纯虚函数,const 等- -
- 项目中的错误:const对象只能调用const函数
- C++中的const对象和const成员函数
- C++中的const成员函数和const类对象
- oc中的Set函数、Get函数、点语法和类方法等
- 关于c++中的const ,包括void fool() const;这个函数中的const的作用
- 关于RegSetValueEx函数中的CONST BYTE参数
- 函数形参中的const引用
- 一个简单的wince.net流驱动模板
- [原创]EJB的复合主键定制规则!!!
- 对Ogre的研究(一)
- 如何用VB6制作光盘自启动程序!
- Understanding Templates in ASP.NET
- 函数、方法等中的const?
- Linux下Oracle的启动方法
- 捆绑MAC和IP地址
- 安装 cygwin
- 确保程序只有一个实例在运行(C#) (收藏)
- 定制你文件夹的新图标
- 77-83年出生的进来看看听听
- Windows 2000/NT一些命令的使用
- 又是周末