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;
}

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

相关推荐
basketball6161 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++
Fre丸子_3 小时前
自定义文件夹选取功能
c++
思麟呀5 小时前
C++工业级日志项目(六)异步日志器
linux·c++·windows
PAK向日葵5 小时前
从零实现 Python 虚拟机(二):S.A.A.U.S.O 的总体架构设计
c++·python
无限进步_5 小时前
【C++】weak_ptr、循环引用与线程安全
开发语言·数据结构·c++·算法·安全
咩咦6 小时前
C++学习笔记30:友元类、内部类和封装
c++·学习笔记·类和对象·封装·内部类·友元类·friend
黄小白的进阶之路7 小时前
C++提高编程---3.6 STL-常用容器-queue 容器【P213~P214】
c++
ID_180079054737 小时前
小红书评论 API 接口详解与实战开发
java·jvm·c++
khalil10207 小时前
代码随想录算法训练营Day-58 图论08 | 拓扑排序精讲、dijkstra(朴素版)精讲
c++·算法·图论·dijkstra·拓扑排序·prim·最短距离
丘山望岳8 小时前
藤萝垂序——二叉搜索树
开发语言·数据结构·c++