c/c++中的const

本文介绍了C++中const的相关知识。const用于修饰只读变量,需在定义时初始化,编辑器常将其保存在符号表。阐述了const修饰一般变量、数组、指针、函数参数和返回值的用途,还说明了在C++里const修饰类成员函数的情况及相关调用规则和原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一:const简介
  • const修饰只读变量,必须在定义的同时进行初始化
  • 编辑器通常不为普通的const只读变量分配内存空间,而是将他们保存在符号表中。
二:const的用途
1.修饰一般变量
const int i=0;
const int j=0;
2.修饰数组
int const arr1[]={1,2,3,4,5};
const int arr2[]={1,2,3,4,5};
3.修饰指针
const int *p;   //p可变,p指向的对象不可变
int const* p;   //p可变,p指向的对象不可变
int *const p;   //p不可变,p指向的对象可变
const int *const p;  //指针p和p指向的对象都不可变
4.修饰函数的参数
int add(const int a,const int b);
5.修饰函数的返回值
const int add(int a,int b);
//在另一个连接文件中引用const只读变量
extern const int i;//正确的声明
extern const int j=10;//错误!只读变量的值不能更改
const在C++中的使用
cosnt 修饰类的成员函数

在C++中将const修饰的成员函数称之为const成员函数,const修饰类成员函数,实际修饰的是该成员函数隐含的this指针,表明在该成员函数中不能对类的任何成员进行修改

  • 编辑器对成员函数的处理
class Date{
public:
	void disPlay()const{
	cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
	}
private:
int _year;
int _month;
int _day;
}
//编辑器对const修饰的成员函数的处理方式
class Date{
public:
	void disPlay(const Date* this){
	cout<<this->_year<<"-"<<this->_month<<"-"<<this->_day<<endl;
	}
private:
int _year;
int _month;
int _day;
}

【总结】
1.const的成员函数不能调用非const的成员函数
2.非const成员函数可以调用const成员函数
3.const对象不能调用非const成员函数
== 4.非const对象 可以调用所有成员函数==
c++中在函数后面加了const的成员函数可以被非const对象和const对象调用 ,但不加const的成员函数只能被非const对象调用

【原理】
我们都知道在调用成员函数的时候编译器会将对象自身的地址作为隐藏参数传递给函数,在const成员函数中,既不能改变this所指向的对象,也不能改变this所保存的地址,this的类型是一个指向const类型对象的const指针。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值