const关键字表示限定为只读
const int *p ; //表示不能通过指针变量p来改变地址上的值
我们需要写一函数仅仅是接收参数的地址,而不会改变它的值时,就可以使用const.
如一个函数:
void func(constStudent * p); 这样反映出我们需传递Student变量的地址,函数里面不改变它的值,而且我们在传递前,必须初始化变量的值.
char *strcpy(char*dest, const char *src); 可看出src仅仅是取值,不会改变的。而dest没有const的修饰,则会改变它指向空间上的内容.
Int *const p;//表示不能改变指针变量指向的地址.
在c++里的函数成员也可以加上const修饰符,可以限定此函数体内不能改变类对象的所有属性成员.
如:
1
2 #include<iostream>
3
4 using namespacestd;
5
6 class MyCls {
7 private:
8 string name;
9 int id;
10
11 public:
12 MyCls(conststring name)
13 {
14 this->name = name;
15 }
16
17 stringget_name() const
18 {
19 id = 88; //这里对属性成员进行操作
20 returnname;
21 }
22 };
23
24 int main(void)
25 {
26
27 return 0;
编译时发生的错误:
[root@localhost08const]# g++ test.cpp
test.cpp: In memberfunction ‘std::string MyCls::get_name() const’:
test.cpp:19:6:error: assignment of member ‘MyCls::id’ in read-only object
id = 88;
^
C++的函数成员带const修饰符,除了限定函数体内不能改变属性成员的值(局部变量这些还是可以改的)外, 还反馈出此函数仅仅是用于获取属性成员的值.