const 的作用

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的函数。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值