关于c++中const的用法详解

(1)const 与常量连用 

        

#include<stdio.h>

int main()
{
  const int a = 20;
    a=2;///错误 a为常量不可改变;
}

(2)  const 与指针连用

示例:const char *p;(指向常量的指针)

#include<stdio.h>
int main()
{
    char a[100]="asdasd";
    char b[100]="nihao";
    const char *p=a;
    a[0]='c';
    /// p[0]='a';错误 因为p是指向常量的,常量的值不可以改变 ;
      p=b;///正确因为p声明的是指向常量的指针,p的地址是可以改变的 ;
    printf("%s",p); ///error: assignment of read-only location '* p'
}

示例:char* const  p;(常指针)

#include<stdio.h>
int main()
{
    char a[100]="asdasd";
    char b[100]="nihao";
    char *const p=a;///定义常指针
     p[0]='a';///正确 因为p是常指针,作用和普通指针一样,只是不能改变指向 ;
      p=b;///错误 ;
    printf("%s",p);///error: assignment of read-only variable 'p'
}

示例:const char* const *p;

#include<stdio.h>
int main()
{
    char a[100]="asdasd";
    char b[100]="nihao";
    const char *const p=a;///定义指向常量的常指针
     p[0]='a';///错误 因为p是指向常量的常指针,作用和普通指针一样,但是不能改变指向 ,也不能改变其内容;
      p=b;///错误 ;
    printf("%s",p);
}


(3)与#define 不同,const 可以拥有自己的数据类型,所以

  const int a=1;

  等价于 const  a = 1;(仅限整形,但是有的编译器不识别);

 #define不分配内存,const 可分配到栈或堆中

(4)const 与函数连用;

①常值const

#include<stdio.h>
const int plusA_B(const int a,int b)///第一个const没什么用   第二个const 表示a的值是一个常值,不可改变
{
    return a+b;
}
int main()
{
    int a=10,b=5;
    printf("%d\n",plusA_B(a,b));
}

②const函数

#include<stdio.h>
struct A
{
    int AC(const int &a,const int &b) const///必须建到类或结构体内
    {
        return (a+b);
    }
};
int main()
{
    int a=10,b=5;
    A c;
    int x=c.AC(a,b);
    printf("%d\n",x);
}



(5)const修饰类对象表示该对象为常量对象,其中的任何成员都不能被修改。对于对象指针和对象引用也是一样。

const修饰的对象,该对象的任何非const成员函数都不能被调用,因为任何非const成员函数会有修改成员变量的企图。

例如:

class AC

{
   
void f1();

void f2() const;

}

const AC aj;

a.f1(); ×

a.f2(); ///正确

const AC* a = new AC();

a
->f1(); ×

a
->f2(); 正确
常成员只能在初始化列表中赋初值


以上就是我对const的理解,希望大神能够补充~

   




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值