const修饰类的成员

c语言

const是一个只读变量,在C语言中修饰一个标识符时,这个标识符本质依然还是一个变量,但是具有常量属性,不能直接被修改。可以使用数组验证。

(1)const修饰指针

const int *p 相当于const *p*p表示p所指向的内容,所以*p不可改变,p可变
int const *p相当于const *p*p不可改变,p可变
int *const p相当于*const p*p可改变,p不可变,即p++错
const int *const p相当于const *const p

*p不可改变,p不可变

(2)修饰函数参数:void fun(const int i);

(3)修饰函数返回值::const int fun();

(4)在另外一个文件中引用const只读变量,

         extern const int i ;   //正确的声明

         extern const int i = 10;   //错误,只读变量值不可修改

C++

C++普通const用法

一、const修饰类的成员变量

const修饰的成员变量相当于该变量是一个常量,所以只能在初始化列表上初始化。

class Date{
public:
	Date(int year = 1900, int month = 1)
		:_year(year)
		, _month(month)
		, _day(1)
	{}
private:
	int _year;
	int _month;
	const int _day;
};

二、const修饰成员函数

const修饰类的成员函数,实质上修饰的是成员函数影藏得this指针,表示该成员函数不能对类的成员变量做修改,所以const不可以修饰构造函数和析构函数和赋值运算符重载。this指针类型变为const Date* const this。如果还是想要修改某一个变量,可以在变量前面加一个关键字mutable。

//两个函数形成重载,因为this指针类型不一样
void display()const
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}
	void display()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

(1)const对象不可以调用非const函数,只能调用const成员函数,因为非const函数可能修改对象成员变量值。

(2)非const对象可以调用任何成员函数,只不过优先调用非const成员函数。

(3)const成员函数不可以调用非const成员函数,只能调用const成员函数。因为非const成员函数需要this指针。

(4)非const成员函数可以调用任何成员函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_41318405

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值