lesson2(补充)取地址及const取地址操作符重载

个人主页:Lei宝啊

愿所有美好如期而遇


以下两个默认成员函数一般不用重新定义 ,编译器默认会生成。

复制代码
#include <iostream>
using namespace std;

class Date
{

public:

	Date()
		:_year(2023)
		,_month(10)
		,_day(28)
	{}

	Date* operator&()
	{
		return this;
	}

	const Date* operator&() const
	{
		return this;
	}

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

int main()
{

	Date a;
	cout << &a << endl;

	const Date b;
	cout << &b << endl;

	return 0;
}


这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可,只有特殊情况,才需
要重载,比如 想让别人获取到指定的内容!

复制代码
#include <iostream>
using namespace std;

class Date
{

public:

	Date()
		:_year(2023)
		,_month(10)
		,_day(28)
	{}

	Date* operator&()
	{
		return nullptr;
	}

	const Date* operator&() const
	{
		return this;
	}

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

int main()
{

	Date a;
	cout << &a << endl;

	const Date b;
	cout << &b << endl;

	return 0;
}

甚至我们可以返回一个错误的地址(滑稽)

相关推荐
啊阿狸不会拉杆38 分钟前
《算法导论》第 32 章 - 字符串匹配
开发语言·c++·算法
小学生的信奥之路1 小时前
洛谷P3817题解:贪心算法解决糖果分配问题
c++·算法·贪心算法
曙曙学编程2 小时前
stm32——GPIO
c语言·c++·stm32·单片机·嵌入式硬件
△曉風殘月〆2 小时前
Visual Studio中的常用调试功能(下)
c++·ide·visual studio·调试
武当豆豆2 小时前
C++编程学习(第25天)
开发语言·c++·学习
minji...6 小时前
C++ string类(STL简介 , string类 , 访问修改字符)
开发语言·c++
Forward♞6 小时前
Qt——文件操作
开发语言·c++·qt
十五年专注C++开发6 小时前
CMake进阶: CMake Modules---简化CMake配置的利器
linux·c++·windows·cmake·自动化构建
winds~7 小时前
【git】 撤销revert一次commit中的某几个文件
linux·c++
carver w7 小时前
MFC,C++,海康SDK,回调,轮询
开发语言·c++·mfc