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;
}
相关推荐
Starmoon_dhw6 分钟前
题解:P16108 「o.OI R-1」基础博弈练习题
c++·算法·图论
2601_9498163528 分钟前
C++内存对齐与结构体填充深度精讲:底层规则、内存裁剪、适配优化与工程避坑
开发语言·arm开发·c++
王老师青少年编程1 小时前
2026年全国青少年信息素养大赛复赛真题(算法应用主题赛C++初中组:带解析)(7月11日试卷一)【文末附答案和解析】
c++·真题·答案·复赛·2026年·青少年信息素养大赛·算法应用主题赛
大阿明1 小时前
C++智能指针与RAII机制精讲:彻底根治内存泄漏与野指针
java·jvm·c++
一生了无挂1 小时前
C++面向对象核心精讲:类、对象、封装、权限与生命周期全解析
java·jvm·c++
aaPIXa6221 小时前
C++ 用 Claude Code 的 defending-code-reference-harness:C/C++ 内存漏洞自动发现与修复 Pipeline
java·c语言·c++
郝学胜-神的一滴2 小时前
[简化版 GAMES 101] 计算机图形学 17:纹理技术从基础原理到多场景实战应用
c++·unity·游戏引擎·图形渲染·three.js·opengl·unreal
炸薯条!2 小时前
从零开始学C++(4) --类和对象
开发语言·c++·算法
渡我白衣2 小时前
打印宏与socket模块设计
java·linux·开发语言·c++·ide·人工智能·eclipse
blueman888811 小时前
Qt5通过vcpkg中调用时,在debug模式下调试时总是调用release的plugins文件夹中的dll
c++·qt·cmake