1. 定义限定变量类型
用于指针的两种情况:const是一个左结合的类型修饰符.
int const *A; //A可变,*A不可变 int *const A; //A不可变,*A可变
2.限定函数的传递值参数:
void function(const int Var); //传递过来的参数在函数内不可以改变.
3.限定函数返回值型.
const int function(); //此时const无意义 const myclassname function(); //函数返回自定义 类 型myclassname.
a.const int fun1() //这个其实无意义,因为参数返回本身就是赋值。
b. const int * fun2() //调用时const int *pValue = fun2();
//我们可以把fun2()看作成一个变量,即指针内容不可变。
c.int* const fun3() //调用时int * const pValue = fun2();
//我们可以把fun2()看作成一个变量,即指针本身不可变。
4限定函数类型.
void function()const; //常成员函数, Const成员函数不能改变对象的成员函数。
采用const_cast 进行转换。
用法:const_cast <type_id> (expression)
该运算符用来修改类型的const或volatile属性。除了const 或volatile修饰之外, type_id和expression的类型是一样的。
常量指针被转化成非常量指针,并且仍然指向原来的对象;
常量引用被转换成非常量引用,并且仍然指向原来的对象;
常量对象被转换成非常量对象。
const_cast<A&>(a).foo1(); //ok
去掉A的常成员变量的常量性
const_cast<int &>(a.m_count) = 1; //ok
Const 变量必须在初始化成员列表中初始化
Const变量必须在初始化成员列表中初始化