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;
}
相关推荐
郝学胜-神的一滴25 分钟前
Linux系统函数stat和lstat详解
linux·运维·服务器·开发语言·c++·程序人生·软件工程
owCode2 小时前
3-C++中类大小影响因素
开发语言·c++
程序猿Eason3 小时前
U587038 背包 题解
c++·算法·动态规划
爱吃芒果的蘑菇3 小时前
C++之WebSocket初体验
网络·c++·websocket·网络协议
Tipriest_3 小时前
C++ 中 using 的使用方法详解
c++·using
顾晨阳——3 小时前
C/C++字符串
c语言·c++·字符串
深耕AI3 小时前
【MFC实用技巧】对话框“边框”属性四大选项:None、Thin、Resizing、对话框外框,到底怎么选?
c++·mfc
ajassi20003 小时前
开源 C++ QT QML 开发(二十一)多媒体--视频播放
c++·qt·开源
仰泳的熊猫4 小时前
LeetCode:95. 不同的二叉搜索树 II
数据结构·c++·算法·leetcode
liu****5 小时前
笔试强训(六)
数据结构·c++·算法