中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档 | 网通镜像
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 编程语言 > Visual C++ > 综合文章
const用法的体会
作者:未知 时间:2003-03-11 12:12 出处:Blog 责编:chinaitpower
              摘要:const用法的体会


网名:  dskra    绿青虫 Email:  dskra@163.net

const主要是为了程序的健壮型,减少程序出错.
最基本的用法:
const int a=100;        b的内容不变,b只能是100也就是声明一个int类型的常量(#define b =100)
int const b=100;        //和上面作用一样

const指针和引用一般用在函数的参数中
int* m = &a;   //出错,常量只能用常指针
int c= 1;const int*pc = &c;//常指针可指向常量

const int* pa = &a;     //指针指向的内容为常量(就是b的值不变)
int const *a = &b;     //指针指向的内容为常量(就是b的值不变)*p=3//error
int* const a = &b;     //指针为常量,不能更改指针了如 a++但可以改值*p=3;

从这可以看出const放在*左侧修饰的是指针的内容,const放在*右侧修饰的是指针
本身.

const引用的用法和指针一样
int const &  a=b;          和指针一样
const int& a=b;          和指针一样
但没有 int& const a=b 的用法因为引用不能做移位运算,但只是出个warning

const int* const a = &b;   //综合应用,一般用来传递多维的数组
类如: char* init[] = {"Paris","in the","Spring"};
void fun(const int* const a){}
fun(init)//保护参数不被修改

int A(int)const;      //是常函数,只能用在类中,调用它的对象不能改改变成员值
const int A();     //返回的是常量,所以必须这么调用   cosnt int a=A();
int A(const int);  //参数不能改值,可用在任意函数
int A(const int*);
....
int height() const;//常函数只能由常函数调用
int max(int,int) const;
int Max = max(height(),height());

 

const int* pHeap = new int;
delete pHeap;
p = NULL;//出错
我的解决办法是强制类型转换
const int*   pHeap = new int(1);
delete (int*)pHeap;
pHeap = NULL;

目前我就遇到这些问题,那位还有补充的吗

关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有