const,望文生义的来讲,指常量,不可改变的量,根据用在不同的地方,其修饰的对象的不同,作用有所不同,但都是修饰对象的不可改变性。
1,const 变量:表示变量是不可改变的。
const int val=2; 则val在后文中不可被改变
const int *p:表示指针p所指的值不能被改变,也即p所指地址的值不可被改变;
int const * p:同上
int * const p:表示p不能被改变,也即p所指的地址不能被改变
2. const int getInt(){ ...}:则表示函数的返回对象不可被改变
3.void setInt(const int val):表示函数的参数不可被改变
4.void setInt(int val) const{....}::表示其函数内部的成员不可被改变
const.cpp
1 #include<iostream>
2
3 using namespace std;
4
5 class Person{
6 public:
7 char *name;
8 int age;
9 void testConst1(){
10 age++;
11 }
12 void testConst(int val) const{
13 testConst1();
14 age++;
15 int testInt=0;
16 testInt++;
17 }
18 };
19
20
21 int main(){
22 Person p();
23
24 return 0;
25 }
编译错误:
const.cpp: In member function ‘void Person::testConst(int) const’:
const.cpp:13: error: passing ‘const Person’ as ‘this’ argument of ‘void Person::testConst1()’ discards qualifiers
const.cpp:14: error: increment of data-member ‘Person::age’ in read-only structure
</pre><pre name="code" class="cpp">从编译的错误提示可以看到:在const修饰的函数体内,不能改变成员变量的值,不能调用非const的函数。