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

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

相关推荐
blasit1 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_3 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星3 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛4 天前
delete又未完全delete
c++
端平入洛5 天前
auto有时不auto
c++
哇哈哈20216 天前
信号量和信号
linux·c++
多恩Stone6 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马6 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc6 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法