(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的理解,希望大神能够补充~