一、const修饰普通类型的变量
如下:
const int a = 7;
int b = a; //it's right
a = 8; // it's wrong,
a被定义为一个常量,并且可以将a赋值给b,但是不能给a再次赋值。对一个常量赋值是违法的事情,因为a被编译器认为是一个常量,其值不允许修改。
二、const 修饰指针变量
const 修饰指针变量有以下三种情况。
A:const 修饰指针指向的内容,则内容为不可变量。
B:const 修饰指针,则指针为不可变量。
C:const 修饰指针和指针指向的内容,则指针和指针指向的内容都为不可变量。
对于A:
const int *p = 8;
则指针指向的内容8不可改变。简称左定值,因为const位于*号的左边。
对于B:
int a = 8;
int* const p = &a;
*p = 9; //it’s right
int b = 7;
p = &b; //it’s wrong
对于const指针p其指向的内存地址不能够被改变,但其内容可以改变。简称,右定向。因为const位于*号的右边。
对于C:
则是A和B的合并
int a = 8;
const int * const p = &a;
这时,const p的指向的内容和指向的内存地址都已固定,不可改变。
对于A,B,C三种情况,根据const位于*号的位置不同,我总结三句话便于记忆的话,
“左定值,右定向,const修饰不变量”。
三、const参数传递和函数返回值
对于const修饰函数参数可以分为三种情况。
A:值传递的const修饰传递,一般这种情况不需要const修饰,因为函数会自动产生临时变量复制实参值。
#include<iostream>
using namespace std;
void Cpf(const int a)
{
cout<<a;
// ++a; it's wrong, a can't is changed
}
int main(void)
{
Cpf(8);
system("pause");
return 0;
}
B:当const参数为指针时,可以防止指针被意外篡改。
#include<iostream>
using namespace std;
void Cpf(int *const a)
{
cout<<*a<<" ";
*a = 9;
}
int main(void)
{
int a = 8;
Cpf(&a);
cout<<a; // a is 9
system("pause");
return 0;
}
C:自定义类型的参数传递,需要临时对象复制参数,对于临时对象的构造,需要调用构造函数,比较浪费时间,因此我们采取const外加引用传递的方法。
并且对于一般的int ,double等内置类型,我们不采用引用的传递方式。
#include<iostream>
using namespace std;
class Test
{
public:
Test(){}
Test(int _m):_cm(_m){}
int get_cm()const
{
return _cm;
}
private:
int _cm;
};
void Cmf(const Test& _tt)
{
cout<<_tt.get_cm();
}
int main(void)
{
Test t(8);
Cmf(t);
system("pause");
return 0;
}
//结果输出 8
对于const修饰函数的返回值
Const修饰返回值分三种情况。
A:const修饰内置类型的返回值,修饰与不修饰返回值作用一样。
#include<iostream>
using namespace std;
const int Cmf()
{
return 1;
}
int Cpf()
{
return 0;
}
int main(void)
{
int _m = Cmf();
int _n = Cpf();
cout<<_m<<" "<<_n;
system("pause");
return 0;
}
B:const 修饰自定义类型的作为返回值,此时返回的值不能作为左值使用,既不能被赋值,也不能被修改。
C: const 修饰返回的指针或者引用,是否返回一个指向const的指针,取决于我们想让用户干什么。
四、const修饰类成员函数
const 修饰类成员函数,其目的是防止成员函数修改被调用对象的值,如果我们不想修改一个调用对象的值,所有的成员函数都应当声明为const成员函数。注意:const关键字不能与static关键字同时使用,因为static关键字修饰静态成员函数,静态成员函数不含有this指针,即不能实例化,const成员函数必须具体到某一实例。
下面的get_cm()const;函数用到了const成员函数
#include<iostream>
using namespace std;
class Test
{
public:
Test(){}
Test(int _m):_cm(_m){}
int get_cm()const
{
return _cm;
}
private:
int _cm;
};
void Cmf(const Test& _tt)
{
cout<<_tt.get_cm();
}
int main(void)
{
Test t(8);
Cmf(t);
system("pause");
return 0;
}
如果get_cm()去掉const修饰,则Cmf传递的const _tt即使没有改变对象的值,编译器也认为函数会改变对象的值,所以我们尽量按照要求将所有的不需要改变对象内容的函数都作为const成员函数。
如果有个成员函数想修改对象中的某一个成员怎么办?这时我们可以使用mutable关键字修饰这个成员,mutable的意思也是易变的,容易改变的意思,被mutable关键字修饰的成员可以处于不断变化中,如下面的例子。
#include<iostream>
using namespace std;
class Test
{
public:
Test(int _m,int _t):_cm(_m),_ct(_t){}
void Kf()const
{
++_cm; //it's wrong
++_ct; //it's right
}
private:
int _cm;
mutable int _ct;
};
int main(void)
{
Test t(8,7);
return 0;
}
这里我们在Kf()const中通过++_ct;修改_ct的值,但是通过++_cm修改_cm则会报错。因为++_cm没有用mutable修饰。