const 用法
来源:互联网 发布:高并发解决方案java 编辑:程序博客网 时间:2024/04/30 20:56
1.const限定类的成员函数
class CReference:CObject
{
public:
CReference();
virtual ~CReference();
void AddRef() const;
void ReleaseRef() const;
protected:
mutable volatile sys_int32 ref;
}
当成员函数不需要修改类中的变量里,一般都声明为const
如果在编写const成员函数时,不慎修改了数据成员,或者调用了其他非const成员函数,编译器将报错,这大大提高了程序的健壮性。
2.const放在函数括号后表示这个函数是一个const成员函数,它不能修改对象的数据
比如:
类stack 的成员函数GetCount 仅用于计数,从逻辑上讲GetCount 应当为const 函数。编译器将指出GetCount 函数中的错误。
class Stack
{
public:
void Push(int elem);
int Pop(void);
int GetCount(void) const; // const 成员函数
private:
int m_num;
int m_data[100];
};
int Stack::GetCount(void) const
{
++ m_num; // 编译错误,企图修改数据成员m_num
Pop(); // 编译错误,企图调用非const 函数
return m_num;
}
3.const int* a = & [1]
int const *a = & [2]
int* const a = & [3]
如果const位于星号的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量;
如果const位于星号的右侧,const就是修饰指针本身,即指针本身是常量。
因此,[1]和[2]的情况相同,都是指针所指向的内容为常量,这种情况下不允许对内容进行更改操作,如不能*a = 3
[3]为指针本身是常量,而指针所指向的内容不是常量,这种情况下不能对指针本身进行更改操作,如a++是错误的
[4]为指针本身和指向的内容均为常量
- const用法
- const用法
- const用法
- const用法
- const用法
- const 用法
- const用法
- const 用法
- const用法
- const用法
- const用法
- const用法
- const用法
- const用法
- CONST用法
- const用法
- const用法
- const用法
- Rob Hess的SIFT算法的C语言实现(基于OpenCV)
- 四种操作xml的方式: SAX, DOM, JDOM , DOM4J
- asp.net Repeater 编辑
- get与post的区别
- 怎样设计抽象类
- const 用法
- Spring Security-2.0导航-基础篇,又添两章
- java日记
- 让时间来证明
- C#开源资源大汇总
- jsp+mysql编码问题的一种解决方案
- delphi 从URL地址中获得文件名
- 屏幕取坐标程序-用于使用Robot类函数时的坐标确定
- 各位,看好你的手机SIM卡