const成员函数

const成员函数

cpp 复制代码
//const成员函数
#include <iostream>
using namespace std;

class Date
{
public:
	void Print()const //void Print(Date* const this); 这里修饰d2的是 Date
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	}


	//构造会频繁调用,所以直接放在类里面定义,作为inline
	Date(int year = 1, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}

	// d1 > d2;
	bool operator>(const Date& d) const  //这里的const(能加就加)  A 修饰的是this指向的内容,也就是保证了成员函数内部不会修改成员变量   B const对象和 非const对象都可以调用这个成员函数。
	{
		if ((_year > d._year)
			|| (_year == d._year && _month > d._month)
			|| (_year == d._year && _month == d._month && _day > d._day))
			return true;
		else
			return false;
	}

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

//只有指针和引用之间才存在 权限的放大和缩小(控制同一个变量的权限)【指针:实参取地址,形参接收地址】【引用:实参传本身,形参接收别名】

void TestDate1()
{
	Date d1(2022, 7, 25);
	const Date d2(2022, 7, 26);
	d1.Print(); //形参传给实参是:&d1--- this [类型是Date* 传给 Date* ]
	d2.Print(); //这里的形参传给实参是:&d2--- this [类型是const Date* 传给 Date* ],造成权限放大

	d1 > d2;  //形参传给实参是:&d1--- this[类型是 Date* 传给 Date* ];  d2---  const Date& d[类型是Date 传给const Date& ]
	d2 > d1;  //形参传给实参是:&d2--- this[类型是const Date* 传给 Date* ](权限放大);  d1--- const Date& d[类型是 类型是 Date 传给const Date&  ]

	 //解决方法:将 Date* this 转化为 const Date* this
}


int main()
{
	TestDate1();

	return 0;
}
相关推荐
HAPPY酷22 分钟前
C++ 成员指针(Pointer to Member)完全指南
java·c++·算法
Sunsets_Red27 分钟前
浅谈随机化与模拟退火
java·c语言·c++·python·算法·c#·信息学竞赛
星火开发设计1 小时前
模板参数:类型参数与非类型参数的区别
java·开发语言·前端·数据库·c++·算法
忘梓.1 小时前
二叉搜索树·极速分拣篇」:用C++怒肝《双截棍》分拣算法,暴打节点删除Boss战!
开发语言·c++·算法
闻缺陷则喜何志丹1 小时前
【C++DFS 马拉车】3327. 判断 DFS 字符串是否是回文串|2454
c++·算法·深度优先·字符串·力扣·回文·马拉车
晨非辰1 小时前
【数据结构入坑指南(三.1)】--《面试必看:单链表与顺序表之争,读懂“不连续”之美背后的算法思想》
数据结构·c++·人工智能·深度学习·算法·机器学习·面试
旖旎夜光1 小时前
哈希(14)(下)
数据结构·c++·学习
拾光Ծ1 小时前
哈希表进阶:挑战用哈希桶封装unordered_set和unordered_map,帮你深度理解迭代器!!!
数据结构·c++·哈希算法·散列表
给我一瓶哇哈哈呀1 小时前
[ROS2] CMU团队的Autonomous Exploration算法+MID-360部署到实车记录
c++·自动驾驶
草莓熊Lotso1 小时前
《算法闯关指南:优选算法--滑动窗口》--15.串联所有单词的子串,16.最小覆盖子串
开发语言·c++·人工智能·算法