const declaration//常量声明
member-function const//修饰类成员函数
When modifying a data declaration, the const keyword specifies that the object or variable is not modifiable. When following a member function's parameter list, the const keyword specifies that the function doesn't modify the object for which it is invoked.
就是说,const仅保证被修饰的成员函数所在的类的成员变量不被修改,其它变量(如该函数的参数和该函数中声明的变量都在保护范围之外)
试验代码:
#include <iostream>
using namespace std;
class Plural
{
public:
void show(int * a_Operand, int a_InTest) const;
private:
int m_RealNum;
};
void Plural::show(int * a_Operand, int a_InTest) const//测试const与函数的搭配用法
{
int i = 0;
cout << i << endl;
cout << *a_Operand << endl;
a_InTest = 6;
a_Operand = &i;
//m_RealNum = 3.0;
i = 2;
cout << i << endl;
cout << *a_Operand << endl;
cout << a_InTest << endl;
}
int main(void)
{
Plural newOne;
int test = 12;
newOne.show(&test, test);
return 0;
}
此时运行正常,当去掉show成员函数中的注释符“//”时就报错了。
每个类的成员函数(除了静态函数外)都回带有一个指向本身对象的this指针作为自己的第一个形参,是隐形的,例如类 class Exam{
int m_i;int m_p;
void set(int i,int j){ m_i = i;m_p = j;}
}
其成员函数set表面上看有两个int类型的参数,实际上还带有一个指向调用对象的this指针,即 该函数应该是
void set (Exam* this,int i,int j){ this.m_i = i;this.m_p = j;}
若为常成员函数,即 函数变为void set(Exam *this,int i,int j)const; 该const修饰的函数的第一个参数,即修饰指向本身对象的指针,变为const Exam* this;从而this指针变为指向常量的指针,这样的话 在常成员函数中去修改类的数据成员的话,就变成的试图去修改常量,当然是错误的。而函数中声明的其他变量由于没有受到const修饰,是可以更改的。
const
(1)可以定义const 常量
(2)const 可以修饰函数的参数、返回值,甚至函数的定义体。被const 修饰的东
西都受到强制保护,可以预防意外的变动,能提高程序的健壮性。
Const int * 表示指针所指向的内存中的值不能变
Int *const 表示指针不能再指向其它内存
Const* int 没有这种用法
Int const * 跟 const int * 是一样的。
定义函数返回值类型为const,表示 返回值不能作为左值使用。