const在C++中的应用

const在c++中使用比较广泛,主要起着限定的作用,即在程序运行过程中限定的内容不会去改变别的变量或者自身改变,接下来具体介绍const的用法
#1 const在常量的应用
这里主要是int const+常量const int+常量可以替换使用
下面在程序中试图修改常量的值

int main(void)
   {  
   int const a[7]; //错误必须赋初值
   const int m=7;//正确
   m=8;//错误表达式必须是可修改的左值
   system("pause"); 
   return 0;
   }

#2.const对指针的限制
这里主要有两个概念,指针常量常量指针,区别在于const在指针限定符* 的左侧或是右侧
##(1)指针常量
const在* 的左侧定义为const int* a或者int const* a,因为int const和const int表达效果一致
在使用中的限制如下

int main(void)
   {  
   int y=5;
   int const *a=&y; //正确定义
   int s=9;
   a=&s;//正确,限定了指针的值不能改变,但是可以改变指向
   *a=9;//错误 不能对指针的值进行修改
   cout<<*a<<endl;
   system("pause"); 
   return 0;
   }

##(2)常量指针
此与上述恰恰相反,const位于* 的右侧,记作int* const a
可以对指针的内容进行直接修改,但是不能改变指向,具体应用如下

int main(void)
   {  
   int y=5;
   int* const a=&y; //正确定义
   int s=9;
   a=&s;//错误,不能改变指向
   *a=9;//正确 可以对指针的值进行修改
   cout<<*a<<endl;
   system("pause"); 
   return 0;
   }

##(3)双重限制
限定指向和内容均不能修改
记作const int* const a

 const int* const a=&y; //正确定义
   int s=9;
   a=&s;//错误,不能改变指向
   *a=9;//错误 不可以对指针的值进行修改

#3.const在函数中的应用
##(1)作为形参
当const作为形参时例如下列格式
int y(const int& a)
此时主要是限制对传入参数进行改动,防止函数运行时改变了引用的数据
例子如下

int y(const int& a)
{
   int s;
   s=a;//正确,可以作为右值
   a=8;//错误,不能对其进行修改
}

##(2)限定函数的返回值
值传递方式
函数会把返回值复制到外部临时的存储单元中,加const 修饰没有任何价值。
指针传递
函数返回值(即指针)的内容不能被修改,例如const char* count(char* str);
则调用的时候应当使用const char *str = count(str1);
引用传递
引用传递一般应用在类的重载函数中,例如对“=”进行重载,使用中加入const可以防止链式赋值

Ccreate(int m):m(m){}
	const Ccreate& operator=(const Ccreate &y)
   {
      this->m=y.m;
   }
   int getnum()
   {
      return m;
   }
private:
   int m;
};
int main(int argc, char* argv[])
{
   {
    Ccreate a(5);
    Ccreate b(2);
    Ccreate c(1);
    (c=b)=a;//失败,不可以进行赋值,改变了b的返回值
    //c=b=a //成功,可以进行链式
    cout<<c.getnum()<<endl;
   }
	
   system("pause");
   return 0;
}

#4在类中的应用
##(1)const成员函数不可以修改对象的数据,这种应用为了确保类中成员的安全性,使用方法在成员函数尾部写上const
示例如下

class Ccreate 
{
public:
Ccreate(int m):m(m){}
	const Ccreate& operator=(const Ccreate &y)
   {
      this->m=y.m;
   }
   int getnum()const//错误,不能修改类中的m值
   {
      m++;
      return m;
   }
private:
   int m;
};
int main(int argc, char* argv[])
{
   {
    Ccreate c(1);
    cout<<c.getnum()<<endl;
   }
   system("pause");
   return 0;
}

##(2)const对于对象的限制,const对象只能访问const成员函数

class Ccreate 
{
public:
Ccreate(int m):m(m){}
	const Ccreate& operator=(const Ccreate &y)
   {
      this->m=y.m;
   }
   void example()
   {
      cout<<"2332"<<endl;
   }
   int getnum()const
   {
      return m;
   }
private:
   int m;
};
int main(int argc, char* argv[])
{
   {
    const Ccreate c(1);
    //c.example();//错误,不能调用
    cout<<c.getnum()<<endl;
    Ccreate b(2);
    b.example();//无限制,可以调用
   }
   system("pause");
   return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值