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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lei宝啊

觉得博主写的有用就鼓励一下吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值