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;
}
相关推荐
玖玥拾2 小时前
C/C++ 基础笔记(十四)多态与模板编程
c语言·c++·多态·模板
Roann_seo%3 小时前
C++文件操作完全指南:从文本读写到二进制文件处理
开发语言·c++
坚果派·白晓明4 小时前
【鸿蒙PC】SDL3 适配:AtomCode + Skills 快速集成 NAPI 测试工具
c++·华为·ai编程·harmonyos·atomcode
凡人叶枫4 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
凡人叶枫5 小时前
Effective C++ 条款16:成对使用 new 和 delete 时要采取相同形式
开发语言·c++·effective c++
不吃土豆的马铃薯6 小时前
C++ 高性能网络缓冲区 Buffer 源码解析
linux·服务器·开发语言·网络·c++
.千余6 小时前
【C++】C++继承入门(下):友元、静态成员与菱形继承的底层逻辑
开发语言·c++·笔记·学习·其他
初中就开始混世的大魔王7 小时前
6 Fast DDS-传输层
开发语言·c++·中间件·信息与通信
代码中介商9 小时前
C++ 智能指针完全指南(三):weak_ptr 与循环引用
开发语言·c++
BestOrNothing_20159 小时前
ROS2 C++ 小车控制完整实战(二):自定义 msg 消息发布与订阅保姆级教程
c++·ros2·subscriber·publisher·msg·topic通信·自定义接口