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;
}
相关推荐
Thera7771 天前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
linux开发之路1 天前
C++高性能日志库开发实践
c++·c++项目·后端开发·c++新特性·c++校招
刻BITTER1 天前
在TRAE 上安装PlatformIO
c++·单片机·嵌入式硬件·arduino
永远都不秃头的程序员(互关)1 天前
C++动态数组实战:从手写到vector优化
c++·算法
水力魔方1 天前
武理排水管网模拟分析系统应用专题5:模型克隆与并行计算
数据库·c++·算法·swmm
OliverH-yishuihan1 天前
在win10上借助WSL用VS2019开发跨平台项目实例
linux·c++·windows
汉克老师1 天前
GESP2025年12月认证C++二级真题与解析(编程题1 (环保能量球))
c++·gesp二级·gesp2级
郝学胜-神的一滴1 天前
Linux进程与线程控制原语对比:双刃出鞘,各显锋芒
linux·服务器·开发语言·数据结构·c++·程序人生
青岛少儿编程-王老师1 天前
CCF编程能力等级认证GESP—C++2级—20251227
java·开发语言·c++
javachen__1 天前
341-十道经典程序设计题目
数据结构·c++·算法