lesson2(补充)关于const成员函数

个人主页:Lei宝啊 

愿所有美好如期而遇


前言:

将const 修饰的 成员函数 称之为 const 成员函数 const 修饰类成员函数,实际修饰该成员函数 隐含的 this 指针 ,表明在该成员函数中不能对类的任何成员进行修改。
class Date
{
public:

	Date()
		:_year(2023)
		,_month(10)
		,_day(28)
	{}

	void print() const   //const限定this指针,相当于const Date* this
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{

	Date a;
	a.print();

	return 0;
}
思考下面的几个问题:
1. const对象可以调用非const成员函数吗?
class Date
{
public:

	Date()
		:_year(2023)
		,_month(10)
		,_day(28)
	{}

	void print1() const   //const限定this指针,相当于const Date* this
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

	void print2()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{

	Date a;
	a.print1();

	const Date b;
	b.print1();

	return 0;
}

编译器甚至都没有给出print2这个函数的选项,答案自然是不能,但为什么不能呢? 

我们定义的对象b是const类型,他的成员变量不能做修改,那他的别名的成员变量也不能修改,而我们上述代码中b对象不能调用print2函数是因为print2函数有权限放大,所以不能调用。
2. 非const对象可以调用const成员函数吗?

 

class Date
{
public:

	Date()
		:_year(2023)
		,_month(10)
		,_day(28)
	{}

	void print1() const   //const限定this指针,相当于const Date* this
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

	void print2()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
	}

private:
	int _year;
	int _month;
	int _day;
};

int main()
{

	Date a;
	a.print1();

	const Date b;
	b.print1();

	Date c;
	c.print2();

	return 0;
}

 

权限放大不可以,但可以有权限的缩小,c对象成员变量可以修改,也可以不修改,他的别名成员变量不可以修改是合理的。

3. const成员函数内可以调用其它的非const成员函数吗?
4. 非const成员函数内可以调用其它的const成员函数吗?

 这里是权限的缩小,是OK的


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Lei宝啊

觉得博主写的有用就鼓励一下吧

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

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

打赏作者

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

抵扣说明:

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

余额充值